I have an xml document which looks like:
<?xml version="1.0" encoding="UTF-8"?> <cbn:PaidOrderNotification xmlns:cbn="http://xml.test.com/3.12.0.0/test.xsd"> <cbn:NotificationDate>2016-08-01T07:28:46.679414Z</cbn:NotificationDate> <cbn:Purchase cbt:Id="95368158" xmlns:cbt="http://xml.test.com/3.12.0.0/testTypes.xsd"> <cbt:Status>Test Order</cbt:Status> <cbt:Items> <cbt:Item cbt:RunningNo="1"> <cbt:ProductId>178732</cbt:ProductId> <cbt:Payment cbt:SubscriptionId="S18767146"> <cbt:CancelUrl>https://store.test.com/</cbt:CancelUrl> <cbt:ChangeUrl>https://test.com/</cbt:ChangeUrl> </cbt:Payment> </cbt:Item> </cbt:Items> <cbt:ExtraParameters /> </cbn:Purchase> </cbn:PaidOrderNotification>
Using C#, I want to get the value inside <cbt:CancelUrl>
tag. How can I do that?
First read the xml
document like:
var doc = new XmlDocument(); doc.LoadXml(_xml);
then you could write:
string CancelUrl = doc.GetElementsByTagName("cbt:CancelUrl")[0].InnerText; string ChangeUrl = doc.GetElementsByTagName("cbt:ChangeUrl")[0].InnerText;
The way to select it, if using Linq to Xml is with defining an XNamespace
object as follows:
XNamespace cbt = "http://xml.test.com/3.12.0.0/testTypes.xsd"; var result = XDocument.Load("data.xml").Root .Descendants(cbt + "CancelUrl") .FirstOrDefault()?.Value; //result - https://store.test.com/
The XmlDocument
class with the XmlNamespaceManager
will support the XPath expressions you need to get the data.
//Load the document XmlDocument order = new XmlDocument(); order.Load("filepath.xml");
Instantiate the namespace manager:
XmlNamespaceManager xmlns = new XmlNamespaceManager(order.NameTable); xmlns.AddNamespace("cbt", "http://xml.test.com/3.12.0.0/testTypes.xsd");
Now you can use the namespace manager to select the information you need. This XPath expression ("//cbt:CancelUrl"
) selects any CancelUrl Node in the entire document, and could be made more specific with a more qualified path.
string xpath = "//cbt:CancelUrl" XmlNode cancelUrl = Order.SelectSingleNode(xpath, xmlns); string value = cancelUrl.InnerText;
You might want to specify the XPath more carefully, and make sure that the selected node isn't null after you selected it.