开发者

How to iterate over xml using linq2xml or Xquery

开发者 https://www.devze.com 2023-02-03 06:31 出处:网络
I have an incoming file with data as <root><![CDATA[<defs><elements> <element><item>aa</item><int>1</int></element>

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&g开发者_StackOverflow社区t;

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).

0

精彩评论

暂无评论...
验证码 换一张
取 消