【问题标题】:Modify Node Value C# with ID使用 ID 修改节点值 C#
【发布时间】:2012-09-12 09:12:17
【问题描述】:

这是我的 XML:

  <?xml version="1.0" encoding="utf-8" ?>
   <Selection>
    <ID>1</ID>
    <Nom>Name 1</Nom>
    <DateReference>0</DateReference>
    <PrefixeMedia>Department</PrefixeMedia>
    <FormatExport>1630</FormatExport>
    <TraceAuto>Oui</TraceAuto>
    <SubID></SubID>
  </Selection>
  <Selection>
    <ID>2</ID>
    <Nom>Name 1</Nom>
    <DateReference>0</DateReference>
    <PrefixeMedia>Department</PrefixeMedia>
    <FormatExport>1630</FormatExport>
    <TraceAuto>1</TraceAuto>
    <SubID>1</SubID>
  </Selection>

我的问题是我想修改例如 &lt;Nom&gt;Name 1&lt;/Nom&gt; 的节点内容,它位于 &lt;Selection&gt;&lt;/Selection&gt;&lt;ID&gt;1&lt;/ID&gt; (按 ID 搜索)

我正在使用 XElement 和 XDocument 进行简单的搜索,但我需要一些帮助来解决上述问题。 (SilverLight 开发

最好的问候。

【问题讨论】:

  • 看看这个:我认为答案是准确的,因为它是 John Skeet:stackoverflow.com/questions/482986/how-to-update-a-xml-node 注意/TLDR:您无法更新 XML 中的单个节点,您将不得不加载文件,在程序中更改该节点,然后重写 XML 文件。
  • 问题到底出在哪里:(1) 找到正确的&lt;Nom&gt; 节点进行更新,(2) 更改节点的值或 (3) 将更改持久保存到您从中获取 XML 的任何位置(文件、数据库、..)?

标签: c# xml silverlight linq-to-xml xelement


【解决方案1】:

另一种方法是使用XmlDocument

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"\path\to\file.xml");

// Select the <nom> node under the <Selection> node which has <ID> of '1'
XmlNode name = xmlDoc.SelectSingleNode("/Selection[ID='1']/Nom");

// Modify the value of the node
name.InnerText = "New Name 1";

// Save the XML document 
xmlDoc.Save(@"\path\to\file.xml");

【讨论】:

    【解决方案2】:

    如果您不知道如何获取正确的&lt;Nom&gt; 节点进行更新,诀窍是首先选择一个包含正确&lt;ID&gt; 节点的&lt;Selection&gt; 节点,那么你可以得到&lt;Nom&gt;节点。

    类似:

    XElement tree = <your XML>;
    XElement selection = tree.Descendants("Selection")
          .Where(n => n.Descendants("ID").First().Value == "1") // search for <ID>1</ID>
          .FirstOrDefault();
    if (selection != null)
    {
      XElement nom = selection.Descendants("Nom").First();
      nom.Value = "Name one";
    }
    

    注意 1:通过使用 Descendants("ID").First(),我希望每个选择节点都包含一个 ID 节点。
    注 2:每个 Selection 节点都包含一个 Nom 节点
    注意 3:现在您仍然需要存储整个 XML,如果您需要的话。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      相关资源
      最近更新 更多