I'm trying to update my XML file. But my parsing code is returning null as a result. This is my code:
StreamResourceInfo xml = Application.GetResourceStream(new Uri("XML/Category.xml", UriKind.Relative));
var doc = XDocument.Load(xml.Stream);
var _result = from x in doc.Elements("Category") where x.Element("Name").Value.Equals("Custom") select x;
_result.First().Element("Subcategories").Value = ",test";
And this is my XML file (very simple):
<Categories>
<Category>
<Name>Custom</Name>
<Subcategories></Subcategories>
</Category>
<Category>
<Name>Popular</Name>
<Subcategories>Most Popular,2nd Popular,3rd Popular</Subcategories>
</Category>
...
</Categories>
This is the problem:
doc.Elements("Category")
That's looking for root elements called Category
(the root element is the only direct child element of the XDocument
). You want:
doc.Root.Elements("Category")
or
doc.Descendants("Category")
Short but complete demonstration:
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
var doc = XDocument.Load("test.xml");
var result = from x in doc.Root.Elements("Category")
where x.Element("Name").Value.Equals("Custom")
select x;
Console.WriteLine(result.Count());
}
}
With the exact XML you've given us, that prints 1.
See more on this question at Stackoverflow