C# 读取和写入具有名称空间的XML文件,而无需遍历每个元素

C# 读取和写入具有名称空间的XML文件,而无需遍历每个元素,c#,xml,C#,Xml,目前,我正在编写一个XML。虽然我确实可以写入XML文件,但我只希望在的“Fruit”标记中写入,并且保持“节点下的信息不动 此外,我希望修改国家标签内的“代码”标签,而不是它之外的标签 以下是XML文件内容(URL是一个伪造的URL,我必须对其进行清理): 以下是当前代码: XDocument xdoc = XDocument.Load(NewFilePath); foreach (XElement element in xdoc.Descendants()) { switch (el

目前,我正在编写一个XML。虽然我确实可以写入XML文件,但我只希望在的“Fruit”标记中写入,并且保持“节点下的信息不动

此外,我希望修改国家标签内的“代码”标签,而不是它之外的标签

以下是XML文件内容(URL是一个伪造的URL,我必须对其进行清理):

以下是当前代码:

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";

这不是简单地隐藏迭代,而是消除它吗?请注意,OP并不清楚他们是在寻找无迭代的源代码还是无循环的运行时。
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";