简体   繁体   中英

Add an element at a specific point with XDocument?

I want to add an element at a certain point. See comments in the code.

<Country>
  <State>
    <Coordinate point="foo" /> <!-- That worked.-->
    <Cali>
        <Coordinate point="bar" /> <!-- How does that work in this case?-->
    </Cali>
  </State>
</Country>

So far my code:

var doc = XDocument.Load(test.xml);
var coordinateElement = new XElement("Coordinate");
coordinateElement.Add(new XAttribute("point", "foo"));

doc.Root.Element("State").Add(coordinateElement);
doc.Save(test.xml);

That worked fine to add an element <Coordinate> after <State> .

But when i want to add it after <Cali> ...

var doc = XDocument.Load(test.xml);
var coordinateElement = new XElement("Coordinate");
coordinateElement.Add(new XAttribute("point", "bar"));

doc.Element("State").Add(coordinateElement);
doc.Save(test.xml);

I get the following error: 'Object reference not set to an instance of an object.'

As the great Jon Skeet pointed out, in your second statement the doc is missing the Root , to prevent the null reference.

Also Element does only look at direct children, so you first need to get to the State node and then to the Cali node. All in all it should look something like this:

doc.Root.Element("State").Element("Cali").Add(coordinateElement);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM