[英]Reading and writing to an XML file with a namespace without iterating through every element
目前,我正在寫XML。 雖然我確實可以寫入XML文件,但我只希望在“ Fruit”標簽內寫入,而保持“ NODE ”下的信息不變。
此外,我希望修改國家/地區代碼中的“代碼”代碼,而不是其外部的代碼。
這是XML文件的內容(URL是我必須清理的虛假URL):
<?xml version="1.0" encoding="utf-8"?>
<Native xmlns="URL" version="2.0">
<Header>
<OwnerCode>Bob</OwnerCode>
</Header>
<Body>
<Fruit version="2.0">
<Thing Action="INSERT">
<Name></Name>
<Color></Color>
<Size></Size>
<CountryCode TableName="SQL_Name">
<Code></Code>
</CountryCode>
<Code></Code>
</Thing>
</Fruit>
</Body>
<NODE>
<Name></Name>
<Color></Color>
<Size></Size>
</NODE>
</Native>
這是當前代碼:
XDocument xdoc = XDocument.Load(NewFilePath);
foreach (XElement element in xdoc.Descendants())
{
switch (element.Name.LocalName)
{
case "Name":
element.Value = "Apple";
break;
case "Color":
element.Value = "Red";
break;
case "Size":
element.Value = "Big";
break;
}
}
xdoc.Save(NewFilePath);
您必須先指定所需的父代,然后才能獲取后代。 您可以應用相同的邏輯來修改Code
標簽:
XDocument xdoc = XDocument.Load(NewFilePath);
XNamespace xn = "URL";
foreach (XElement element in xdoc.Descendants(xn+"Fruit").Descendants())
{
switch (element.Name.LocalName)
{
case "Name":
element.Value = "Apple";
break;
case "Color":
element.Value = "Red";
break;
case "Size":
element.Value = "Big";
break;
}
}
foreach(var el in xdoc.Descendants(xn+"Code").Where(x=>x.Parent.Name==xn+"CountryCode"))
{
el.Value="Test";
}
xdoc.Save(NewFilePath);
無需循環遍歷元素,而是可以直接對其進行尋址。
XNamespace ns = "URL";
XElement thing = doc.Element(ns + "Native").Element(ns + "Body").Element(ns + "Fruit").Element(ns +"Thing");
thing.Element(ns + "Name").Value = "Apple";
thing.Element(ns + "Color").Value = "Red";
thing.Element(ns + "Size").Value = "Big";
thing.Element(ns + "CountryCode").Element(ns + "Code").Value = "new-country-code";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.