简体   繁体   中英

Read xml Element value WITHOUT cdata?

I have this simple xml :

<AllBands>
  <Band>
    <Name ID="1234" started="1962">Beatles<![CDATA[lalala]]></Name>
    <Last>1</Last>
    <Salary>2</Salary>
  </Band>
  <Band>
    <Name ID="222" started="1968">Doors<![CDATA[lalala]]></Name>
    <Last>1</Last>
    <Salary>2</Salary>
  </Band>
</AllBands>

I want to read the " bealtes " value from the Name element

by

using (var stream = new StringReader(result))
{
    XDocument xmlFile = XDocument.Load(stream);
    var query = from c in xmlFile.Descendants("Band") select c;

    foreach (XElement band in query)
    {
     if (band.Element("Name").Value ==...) // this expression is beatleslalala 
                                           // and not beatles alone...

    }
}

why is that? why does he includes the cdata? How can i get the "beatles" only?

Your <Name> element node contains two child nodes: a text node and a CDATA node.

The Value of an element node is all values of its child nodes concatenated.

If you want the value of the text node, you need to get the Value of the text node, not the element.

Note that it's quite unusual to distinguish between text nodes and CDATA nodes when reading an XML file. The author of the file should be able to use whichever they like.

You have a text value and a CDATA Node as children of Name is why.

If you dig about inside the name node you'll be able to find the two parts but you might want to rework your xml structure

<Name ID="1234" started="1962">Beatles<Lyrics><![CDATA[lalala]]></Lyrics></Name>

As it is, an xsd for it is going to be messy.

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