Parsing complex XML with C#

后端 未结 2 608
渐次进展
渐次进展 2021-01-20 00:52

I am trying to parse a complex XML with C#, I am using Linq to do it. Basically, I am doing a request to a server and I get XML, this is the code:

XElement x         


        
2条回答
  •  情书的邮戳
    2021-01-20 01:50

    To write a query on XML that is in a namespace, you must use XName objects that have the correct namespace. For C#, the most common approach is to initialize an XNamespace using a string that contains the URI, then use the addition operator overload to combine the namespace with the local name.

    To retrieve the value of the link_id element you will need to declare and use an XML namespace for the test:link element.

    Since you did not show the namespace declaration in your example XML, I am going to assume it is declared somewhere elese in the XML document. You need to locate the namespace declaration in the XML ( something like xmlns:test="http://schema.example.org" ) which is often declared in the root of the XML document.

    After you know this, you can do the following to retrieve the value of the link_id element:

    XElement xdoc = XElement.Parse(e.Result);
    
    XNamespace testNamespace = "http://schema.example.org";
    
    this.newsList.ItemsSource = from item in xdoc.Descendants("item")
      select new ArticlesItem
      {
        Title       = item.Element("title").Value,
        Link        = item.Element(testNamespace + "link_id").Value,
        Description = this.Strip(item.Element("description").Value).Substring(0, 200).ToString()                            
      }
    

    See the XNamespace and Namespaces in C#, and How to: Write Queries on XML in Namespaces for further information.

提交回复
热议问题