读取和写入具有命名空间的 XML 文件,而无需循环访问每个元素



目前,我正在写入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";

最新更新