[英]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.