简体   繁体   English

使用名称空间读取和写入XML文件,而无需遍历每个元素

[英]Reading and writing to an XML file with a namespace without iterating through every element

Currently, I am writing to an XML. 目前,我正在写XML。 While I can indeed write to the XML file, I wish to only write inside the "Fruit" tag, and leave the info under " NODE " untouched. 虽然我确实可以写入XML文件,但我只希望在“ Fruit”标签内写入,而保持“ NODE ”下的信息不变。

Additionally, I wish to modify the "Code" tag that's within the country tag, not the one outside of it. 此外,我希望修改国家/地区代码中的“代码”代码,而不是其外部的代码。

Here's the XML file contents (the URL is a bogus one that I had to sanitize): 这是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>

Here's the current code: 这是当前代码:

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

You have to first specify the parent desired to only then get the descendants. 您必须先指定所需的父代,然后才能获取后代。 The same logic you could apply to modify the Code tag: 您可以应用相同的逻辑来修改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);

Instead of looping over elements, they can be addressed directly. 无需循环遍历元素,而是可以直接对其进行寻址。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM