2

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
  • Can you post the sample code you've already written? Commented May 1, 2010 at 16:14

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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);
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.