简体   繁体   中英

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

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

When complete, the xml file (on disk) should look like:

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

These two look marginally promising:

Overwrite a xml file value

Setting attributes in an XML document

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 . That way you do not need to load the whole xml in memory.

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

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.

After you have found the nodes you want to update you can reassign the attribute value as needed with a normal assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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