簡體   English   中英

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

[英]Add an element at a specific point with XDocument?

我想在某個點添加一個元素。 請參閱代碼中的注釋。

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

到目前為止我的代碼:

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

<State>之后添加元素<Coordinate>效果很好。

但是當我想在<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);

我收到以下錯誤:“對象引用未設置為 object 的實例。”

正如偉大的Jon Skeet指出的那樣,在您的第二個聲明中, doc缺少Root ,以防止 null 參考。

此外 Element 只查看直接子節點,因此您首先需要到達State節點,然后到達Cali節點。 總而言之,它應該看起來像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM