简体   繁体   中英

How to iterate over xml using linq2xml or Xquery

I have an incoming file with data as

<root><![CDATA[<defs><elements>
      <element><item>aa</item><int>1</int></element>
      <element><item>bb</item><int>2</int></element>
      <element><item>cc</item><int>3</int></element>
</elements></defs>]]></root>

writing multiple foreach( xElement x in root.Elements ) seems superfluous !

looking for a less verbose method preferably using C#

UPDATE - yes - the input is in a CDATA, rest assured it's not my design and i have ZERO control over it !

Assuming that nasty CDATA section is intentional, and you're only interested in the text content of your leaf elements, you can do something like:

XElement root = XElement.Load(yourFile);
var data = from element in XElement.Parse(root.Value).Descendants("element")
           select new {
               Item = element.Elements("item").First().Value,
               Value = element.Elements("int").First().Value
           };

That said, if the code that generates your input file is under your control, consider getting rid of the CDATA section. Storing XML within XML that way is not the way to go most of the time, as it defeats the purpose of the markup language (and requires multiple parser passes, as shown above).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM