简体   繁体   English

使用 XDocument 在特定点添加元素?

[英]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> .<State>之后添加元素<Coordinate>效果很好。

But when i want to add it after <Cali> ...但是当我想在<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.'我收到以下错误:“对象引用未设置为 object 的实例。”

As the great Jon Skeet pointed out, in your second statement the doc is missing the Root , to prevent the null reference.正如伟大的Jon Skeet指出的那样,在您的第二个声明中, doc缺少Root ,以防止 null 参考。

Also Element does only look at direct children, so you first need to get to the State node and then to the Cali node.此外 Element 只查看直接子节点,因此您首先需要到达State节点,然后到达Cali节点。 All in all it should look something like this:总而言之,它应该看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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