Reputation: 19587
I have this xml
<genral>
<mynode id="1">
<first id="1.1">
<nodechild-first id="1.1.1"></nodechild-first>
<nodechild-seconed id="1.1.2"></nodechild-seconed>
</first>
</mynode>
</genral>
I need to rename one of the nodes name,for example change the name of <first>
to <f>
or the <nodechild-first>
to <c-f>
How can I do it using asp.net(XmlDocument) .
the values of destination name node and the new name node, is represented by two string variables.
Thanks for any help
Upvotes: 0
Views: 4756
Reputation: 19587
OK This is my solution for the problem,im my xml there isn't same node name twice(so every one sholud make his own changes,but the main idea is the same
Sub btnc_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnc.Click
Dim xmldoc As XmlDocument = New XmlDocument()
xmldoc.Load(Server.MapPath("yuor xml path"))
Dim nodee As XmlNodeList = xmldoc.GetElementsByTagName(tempstr)//path to node
' parent element of the element we want to replace
Dim parentElement As XmlNode = nodee(0).ParentNode
' element we want to replace
Dim oldXmlNode As XmlNode = nodee(0)
' new element
Dim newXmlElement As XmlElement = xmldoc.CreateElement(txtdes.Value)
Dim temp As XmlAttribute = oldXmlNode.Attributes("id")//adding attirbute old->new
newXmlElement.Attributes.Append(temp)
Dim node As XmlNode = oldXmlNode.FirstChild node
buildtree(newXmlElement, xmldoc, node)//copy first child to new
node = node.NextSibling /taking next Sibling
While Not IsNothing(node)//while node has brothers
buildtree(newXmlElement, xmldoc, node)/copy Sibling old->new
node = node.NextSibling //next Sibling
End While
parentElement.ReplaceChild(newXmlElement, oldXmlNode)// making the switch
xmldoc.Save(Server.MapPath("path"))
End Sub
Sub buildtree(ByVal newnode As XmlNode, ByVal xmldoc As XmlDocument, ByVal oldxmlnode As XmlNode)
newnode.AppendChild(xmldoc.ImportNode(oldxmlnode, True))
End Sub
Upvotes: 0
Reputation: 883
You can't just change name of a allready existing node. What you need to do is.
I should also tell you that you can't rename the root node, if you want to do that you either need to switch make 3. after 5. or you need to insert it into a new XMLDocument because it won't allow you to have two root nodes.
Regards
Upvotes: 1
Reputation: 1397
Sorry misunderstood.... Thinking about it.
By the looks of it you cant change a nodes name. You could try making a new XML file and give them different names there or creating new nodes.
OLD *
Use this in the class where you want to do it:
Private Shared ReadOnly XMLFile As String = "LinkToYourXML"
Dim mappingDataXml As System.Xml.XmlDocument = New System.Xml.XmlDocument mappingDataXml.Load(XMLFile)
For Each node As System.Xml.XmlNode In mappingDataXml.SelectNodes("/genral/mynode/first")
node.SelectSongleNode("nodechild-first").InnerText = "The text you want to have in there."
Next
Hope this could be of any help :)
OLD *
Upvotes: 0