I have a simple XML
<AllBands> <Band> <Beatles ID="1234" started="1962">greatest Band<![CDATA[lalala]]></Beatles> <Last>1</Last> <Salary>2</Salary> </Band> <Band> <Doors ID="222" started="1968">regular Band<![CDATA[lalala]]></Doors> <Last>1</Last> <Salary>2</Salary> </Band> </AllBands>
However ,
when I want to reach the "Doors band" and to change its ID :
using (var stream = new StringReader(result)) { XDocument xmlFile = XDocument.Load(stream); var query = from c in xmlFile.Elements("Band") select c; ...
query
has no results
But
If I write xmlFile.Elements().Elements("Band")
so it Does find it.
What is the problem ?
Is the full path from the Root needed ?
And if so , Why did it work without specify AllBands
?
Does the XDocument
Navigation require me to know the full level structure down to the required element ?
XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.
The XDocument class contains the information necessary for a valid XML document, which includes an XML declaration, processing instructions, and comments. You only have to create XDocument objects if you require the specific functionality provided by the XDocument class.
The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.
Elements()
will only check direct children - which in the first case is the root element, in the second case children of the root element, hence you get a match in the second case. If you just want any matching descendant use Descendants()
instead:
var query = from c in xmlFile.Descendants("Band") select c;
Also I would suggest you re-structure your Xml: The band name should be an attribute or element value, not the element name itself - this makes querying (and schema validation for that matter) much harder, i.e. something like this:
<Band> <BandProperties Name ="Doors" ID="222" started="1968" /> <Description>regular Band<![CDATA[lalala]]></Description> <Last>1</Last> <Salary>2</Salary> </Band>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With