C# - Get value from a specific tag in XML document

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

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?

回答1:

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;


回答2:

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/


回答3:

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.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!