1
我正在創建xml,方法是採用skelton xml並使用值填充節點,並在需要時添加xml之間的新節點。我正在以下面的方式做,感覺...效率不高。 有沒有更好的方法來滿足我的要求?使用Linq創建xml更有效的方法
樣品普通產品XML:
<root>
<ProductInformation>
<Name></Name>
<ProductId></ProductId>
<Description></Description>
<Details>
<TabName></TabName>
<DetailList>
<Add>
<Type></Type>
<Information></Information>
</Add>
</DetailList>
</Details>
</ProductInformation>
</root>
代碼:
XDocument xmlDoc = XDocument.Load(Server.MapPath("/PlainProduct.xml"));
xmlDoc.Element("root").Element("ProductInformation").SetElementValue("Name","iPhone");
xmlDoc.Element("root").Element("ProductInformation").SetElementValue("ProductId", "123456");
foreach (XElement detail in xmlDoc.Descendants("ProductInformation").Elements("Details"))
{
detail.SetElementValue("TabName", "Specifications");
foreach (XElement x in detail.Elements("DetailList"))
{
//Update node value and here the node already exists in plain skelton xml
x.Element("Add").SetElementValue("Type","Plastic");
x.Element("Add").SetElementValue("Information", "24 Carat");
//Added below two new nodes dynamically if my backend has more items of details programmatically
x.Add(new XElement("Add",
new XElement("Type", "Fabric"),
new XElement("Information", "Smooth")));
x.Add(new XElement("Add",
new XElement("Type", "Finishes"),
new XElement("Information", "Rogh")));
}
}
@bryanjonket謝謝老兄....它看起來更清潔,易於維護.... – DotNetDeveloper 2011-05-19 19:38:07
@bryanjonket ......我碰到的另一個問題就來了,現在,我填XML使用你的靜態方法,現在想編輯或更新XML節點值,所以我怎麼找到實際的節點?比如說我想更新DetailsList的第二個重複節點和Add> Type值的第二個子節點。 – DotNetDeveloper 2011-05-19 20:07:20