简体   繁体   中英

Update/erase a given string in XML using C#

So I'm trying to map a Microsoft Excel file and after that extract the xml file from it.

After I do this I end up with a XML file that goes on something like this:

 <domain>
    <prio>priority</prio>
    <fund>Fundamentals</fund>
 </domain>
 **<onething />**
 <domain>
    <prio>priority</prio>
    <fund>Fundamentals</fund>
 </domain>
 **<anotherthing />**

Notice the tags in between ** **. Microsoft Excel generates them automatically in fields which have no values.

This tags can be any tag on the xml mapping. So, the only common fact between these tags are the chars "<" "/" and ">. Example: <aBadTag/>

So, I'm writting ac# code and what I want to do is: 1 - Check all the XML file for every occurrence < xxxx /> 2 - remove that tag.

the code I have so far is:

XmlDocument doc = new XmlDocument();

 doc.Load(c:\someXml.xml);

 XmlNodeList stuffNodeList = doc.SelectNodes("//*[starts-with(name(), 'domain')]");  

        foreach (XmlNode stuffNode in stuffNodeList)
        {

                if (doc.InnerXml.Between("<", "/>") != "") {

                    //should have code to delete the entire tag
                }

}

The problem with this is that it returns the WHOLE code between the first "<" in and the last "/>" in and note "line by line".

thank you in advance.

Focus on the items you want do delete:

 XmlNodeList deleteList = doc.SelectNodes("//onething | //anotherthing | //aBadTag");  
 foreach (XmlNode deleteNode in deleteList)
 {
     deleteNode.ParentNode.Remove(deleteNode);
 }

EDIT: For selecting only elements without inner text, use an XPath like //*[not(text())]

You can use linq for that. Select only empty nodes and remove them.

doc.root.Descendants().Where(o => string.IsNullOrEmpty(o.Value()).Select(o => o.ParentNode.Remove(o));

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