简体   繁体   中英

Replacing Part of InnerText in XML

I'm writing a program in VB using visual studio 2010. I'm trying to replace text in an xml but I'm not sure how I can do this.

My xml file looks like this. There are tags with the same name but in different level.

<root>
    //1st example
    <tagA> //outer
        <nameA>something</nameA>
        <tagA>
           <flagA>%replace001%</flagA>
           <flagB>Keep this</flagB>
        </tagA> //inner
    </tagA>
    <tagB>
        some other stuff
    </tagB>
    //2nd example
    <tagA>
        %raplace002%
    </tagA>
</root>

I'm trying to replace the values in surrounded by % , and those are guarenteed under tagA

I wrote my code like this:

replaceList = {"%replace001", "%replace002%"}
For Each str in replaceList
    For Each node in xmlDoc.GetElementsByTagName("tagA")
        node.InnerText = node.InnerText.Replace(str, "success")
    Next
Next

But this caused an issue in the 1st example where it's getting the outter part of the section but not the inner part, which makes the Replace not entirely what I'm looking for.

Can someone help me with this? I basically want to replace the most inner inntertext only.

Note: I'm using XmlDocument , please don't provide answers such as converting the whole xml to String and do simple String.Replace.

Thank you!

Edit:

Sorry I didn't make it clear enough.

There are more children in tagA , and tagA could be a child of another tagA .

I'm looking for more most inner tagA , but it doesn't always mean that it has no children.

To get only inner most <tagA> , you can use SelectNodes() method passing the following XPath as parameter :

//tagA[not(.//tagA)]

Above XPath means select, all <tagA> elements, anywhere in the document, which doesn't have any other <tagA> child element. Change the inner for each loop to be as follow :

For Each node in xmlDoc.SelectNodes("//tagA[not(.//tagA)]")
    node.InnerText = node.InnerText.Replace(str, "success")
Next

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