I have a question. Is it possible to navigate to an specific field in an xml and add elements to it?
I tried this:
XDocument doc = XDocument.Load("myxmldoc.xml");
doc.Element("Table").Element(Product).CreateNavigator().Add(new XElement("Lamp", "Lamp"));
Needless to say it didn’t work. The thing is that I have an xml that looks like this:
<Table>
<Product>
<Chair/>
<Table/>
<ChessBoard/>
</Product>
<Product>
<Chair/>
<Table/>
<ChessBoard/>
</Product>
<Product>
<Chair/>
<Table/>
<ChessBoard/>
</Product>
</Table>
As you can see I have many Product tags and I want to be able to add the item Lamp to an specific node with linq. Every time I add elements with:
doc.Element("Table").Element("Porduct").Add(new XElement("Lamp", "Lamp"));
The Lamp element goes to the first Product node. I want it to go to an specific node, let’s say the second one.
Someone advised me to use:
doc.Element("Table").Element("Porduct").ElementAt(2).Add(new XElement("Lamp", "Lamp"));
But it doesn’t work. Visual Studio 2010 says it doesn’t exist.
You need
Elements("Porduct")(note the s) to useElementAt():It would be a little easier if the Products had something to identify them, like an ID attribute.
(And probably you should fix the typo Porduct / Product)