Replace main node name

This might be a simple question....

I have an xml file:
< xml version="1.0" encoding="UTF-8" >
<Content>
<Element1>ele2</Element1>
<Element2>ele2</Element2>
</Content>

I want to replace Content with Page in my C# application and I tried:
XmlNode firstNode = xmlDoc.SelectSingleNode("Content");
firstNode.LocalName.Replace("Content","Page");

Obviously I am doing it wrong or not understanding it properly, so, I am not getting the desired output. What is the correct api that I should use


Answer this question

Replace main node name

  • Roedeske

    I didn't understand how you want me to use this. LoadXml can be used like LoadXml("<item><name>wrench</name></item>"), so, how could it update an already existing node

    In my example, I did use load like:

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load("file.xml");

    and tried using:

    XmlNode firstNode = xmlDoc.SelectSingleNode("Content");
    firstNode.LocalName.Replace("Content","Page");


  • Ana Azevedo

    hi,

    i'm still learning too , i don't know anyway to rename the xmlnodes but i would do it in different way till i find a way to do that like for example

    to user streamreader to load the xmlfile to normal string and replace the nodes name that i want first then set my file in xmldoc like

    XmlDoc.LoadXml(mystring) instead of

    XmlDoc.Load("filepath.xml")

    hope this helps



  • Hiverness

    hi,

    the problem in the code that you use is that local name or name is readonly property you can't change the node tag by it , and we don't know the class that change the node if there any , anyway you can use stream reader then put the content in xmldoc

    it will be something like this


    string myfiletext;
    using (System.IO.StreamReader mystream = new System.IO.StreamReader("Myxmlfile.xml"))
    {
    myfiletext = mystream.ReadToEnd();
    }
    myfiletext = myfiletext.Replace(
    "<Content>", "<Page>");
    myfiletext = myfiletext.Replace(
    "</Content>", "</Page>");
    System.Xml.
    XmlDocument XmlDoc = new System.Xml.XmlDocument();
    XmlDoc.LoadXml(myfiletext);

    hope this helps



  • Replace main node name