tags:

views:

221

answers:

1

I have an XML doc with a structure like this:

<Book>
    <Title title="Door Three"/>
    <Author name ="Patrick"/>
</Book>

<Book>
    <Title title="Light"/>
    <Author name ="Roger"/>
</Book>

I want to be able to melodramatically add XML nodes to this XML in a particular place. Lets say I wanted to add a Link node as a child to the author node where the name is Roger.

I think it's best if the function containing this logic is passed a param for the name to add an XML node under, please advise and what's the code I need to add XML nodes to a certain place in the XML?

Now I am using .AppendChild() method but it doesn't allow for me to specify a parent node to add under...

+1  A: 

AppendChild will append the node passed in to the node that you invoke it on.

So, if you select the Author node, you can append a new node to it:

XmlNode author = XmlDocument.SelectSingleNode("/Book/Author[@name='Roger']");
author.AppendChild(otherElementToAppend);
Oded
how can i dynamically find the node i want to append a child node to?I wanted to add a Link node as a child to the author node where the name is Roger.
kacalapy
@kacalapy - Answer updated with example
Oded
if all my xml nodes were all <node name="mike"> and thus started "node" can i traverse every node in my xml with XmlNode author = XmlDocument.SelectSingleNode("//node/Author[@name='Roger']");author.AppendChild(otherElementToAppend);
kacalapy
The xpath expression you have would select all `Author` nodes who have a parent `node` and an attribute `name` that is set to `Roger`. Using `SelectSingleNode` would return the first such node.
Oded