简体   繁体   English

覆盖特定的XML属性

[英]Overwrite specific XML attributes

Let's say I have a file like this: 假设我有一个像这样的文件:

<outer>
  <inner>
    <nodex attr="value1">text</attr>
    <nodex attr="value2">text</attr>
  </inner>
</outer>

Basically what I want to do is, in C# (constrained to .net 2.0 here), this (pseudocode): 基本上我想做的是在C#中(这里限制为.net 2.0),这个(伪代码):

foreach node
    if(node eq 'nodex')
        update attr to newvalue

When complete, the xml file (on disk) should look like: 完成后,xml文件(在磁盘上)应如下所示:

<outer>
  <inner>
    <nodex attr="newvalue1">text</attr>
    <nodex attr="newvalue2">text</attr>
  </inner>
</outer>

These two look marginally promising: 这两个看起来有些许希望:

Overwrite a xml file value 覆盖xml文件值

Setting attributes in an XML document 在XML文档中设置属性

But it's unclear whether or not they actually answer my question. 但是还不清楚他们是否真的回答了我的问题。


I've written this code in the meantime: 在此期间,我已经编写了以下代码:

Here's a more minimal case which works: 这是一个更小巧的案例,可以工作:

    public static void UpdateXML()
    {
        XmlDocument doc = new XmlDocument();
        using (XmlReader reader = XmlReader.Create("XMLFile1.xml"))
        {
            doc.Load(reader);
            XmlNodeList list = doc.GetElementsByTagName("nodex");
            foreach (XmlNode node in list)
            {
                node.Attributes["attr"].Value = "newvalue";
            }
        }
        using (XmlWriter writer = XmlWriter.Create("XMLFile1.xml"))
        {
            doc.Save(writer);
        }
    }

The fastest solution would be to use a loop with XmlTextReader / XmlTextWriter . 最快的解决方案是对XmlTextReader / XmlTextWriter使用循环。 That way you do not need to load the whole xml in memory. 这样,您无需将整个xml加载到内存中。

In pseudocode: 在伪代码中:

while (reader.read)
{
   if (reader.Node.Name == "nodex")
       ......

   writer.write ...
}

You can check here for ideas . 您可以在此处查看想法

Here is a sample script that can be run from LinqPad 这是可以从LinqPad运行的示例脚本

var x = @"<outer>
  <inner>
    <nodex attr=""value1"">text</nodex>
    <nodex attr=""value2"">text</nodex>
  </inner>
</outer>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(x);

foreach (XmlNode n in doc.SelectNodes("//nodex"))
{
    n.Attributes["attr"].Value = "new" + n.Attributes["attr"].Value.ToString();
}

doc.OuterXml.Dump();

As starting point you can show us what you have tried, you could use XPATH to select the nodes you want to modify, search for select node by attribute value in xpath. 作为起点,您可以向我们展示您的尝试,可以使用XPATH选择要修改的节点,并通过xpath中的属性值搜索选择节点。

After you have found the nodes you want to update you can reassign the attribute value as needed with a normal assignment. 找到要更新的节点后,可以根据需要使用常规分配来重新分配属性值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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