2

My xml is this:

<Settings>
    <Ss></Ss>
    <Properties>
        <Property>
            <Name>x</Name>
            <Description>xx</Description>
        </Property>
            <Property>
            <Name>y</Name>
            <Description>yyyyy</Description>
            </Property>
    </Properties>
</Settings>

I want to add as a son of Properties an XElement. This is my code:

XDocument xmlDoc1 = XDocument.Load(@"C:\Users\John\Desktop\FileXml.xml");
xmlDoc1.Element("Properties").Add(new XElement(addManyNodes));

But it doesn't work. It throws null reference exception. Why?

1 Answer 1

2

Because the root of the XDocument is <Settings> and the root itself is not <Properties> you get a null value from Element("Properties").

You need to drill down using XDocument.Root or a chain of calls to Element or Descendants. Here are a few options:

// simplest
xmlDoc1.Root.Element("Properties").Add(new XElement(addManyNodes));

// using a chain of Element calls
xmlDoc1.Element("Settings").Element("Properties").Add(...);

Another way to look at it:

<!-- xmlDoc1 -->
<Settings> <!-- .Root or .Element("Settings") -->
    <Ss></Ss> <!-- .Root.Element("Ss") or .Element("Settings").Element("Ss") -->
    <Properties> <!-- .Root.Element("Properties") -->
        <Property> <!-- .Root.Element("Properties").Element("Property") -->

One final note, if addManyNodes is already an array:

xmlDoc1.Root.Element("Properties").Add(addManyNodes);

Once you've made your changes, you should save it to the file:

xmlDoc1.Save(...);
Sign up to request clarification or add additional context in comments.

1 Comment

I've gone ahead and added some additional info about adding multiple nodes and saving the document when you're through making changes.

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.