2011-10-27 112 views
2

我的XML是這樣的:在XML一次添加多個節點

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

我要添加爲屬性的的XElement的兒子。這是我的代碼:

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

但它不起作用。它引發空引用異常。爲什麼?

回答

2

因爲的XDocument的根源是<Settings>和根本身不是<Properties>你從Element("Properties")一個null值。

您需要使用XDocument.RootElementDescendants的調用鏈向下鑽取。這裏有幾個選項:

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

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

另一種方式來看待它:

<!-- 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") --> 

最後要說明的,如果addManyNodes已經是一個數組:

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

一旦您完成了您的更改,you should save it to the file

xmlDoc1.Save(...); 
+0

它的工作:) 但它不會在xml文件中添加。 –

+0

我已經提前添加了一些關於添加多個節點並在進行更改時保存文檔的其他信息。 – user7116

+0

OMG非常感謝你,你真的幫助:) –