简体   繁体   中英

Replace XML node / string

I have two serialized XML objects like:

<car id="1">
  <name>Renault</name>
  <type>
    <gear>Manual</gear>
    <petrol>Gas</petrol>
    <model>11</model>
  </type>
  <status>Available</status>
</car>

And another just being a tag:

<type>
 <gear>Automatic</gear>
</type>

I want to replace the type node from the first object with the node from the second object.

I tried:

string output = Regex.Replace(input, @"<type>(.*)</type>", replacement, RegexOptions.IgnoreCase);

But it doesn't give the desired output. Any suggestions?

You can do this my XmlDocument :

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<car id=\"1\"><name>Renault</name><type><gear>Manual</gear><petrol>Gas</petrol><model>11</model></type><status>Available</status></car>");

var typeNode = xmlDoc.SelectSingleNode("descendant::car[@id='1']/type");

if (typeNode != null) typeNode.InnerText = "<gear>Automatic</gear>";

string str = xmlDoc.InnerXml;

you can use you own function with substring, like this

    private void button1_Click(object sender, EventArgs e)
    {
       MessageBox.Show(NodeReplace(xml, "type",value));
    }

    public string NodeReplace(string xml, string nodeToFind, string newValue)
    {
        int start = xml.IndexOf("<" + nodeToFind);
        int end = xml.IndexOf("</" + nodeToFind + ">");

        string toreplace = xml.Substring(start, end + 3 + (nodeToFind.Length) - start);
        xml = xml.Replace(toreplace, newValue);
        return xml;
    }

but if you want a recomendation, i think is better serialize with a class and simple replace you node like a variable

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