简体   繁体   中英

remove parent if child node has no value

I want to remove parent elements from an XML structure if child is empty. My XML:

<Customers>
<customer>
    <Name>John</Name>
    <Age>25</Age>
    <Status>single</Status>
</Customer>
<customer>
    <Name>Jack</Name>
    <Age></Age>
    <Status></Status>
</Customer>
</Customers>

Should become:

<Customers>
    <customer>
        <Name>John</Name>
        <Age>25</Age>
        <Status>single</Status>
    </Customer>
    </Customers>

my code :

XmlElement element3 = xmlDocument.CreateElement("Age");
        element3.InnerText = str3;
        element1.AppendChild((XmlNode)element3);    
XmlElement element4 = xmlDocument.CreateElement("Status");
        element4.InnerText = str4;
        element1.AppendChild((XmlNode)element4);

How can I remove the parent "customer", if age and status child are empty?

You can use XPath syntax along with SelectNodes() method to get specific nodes from XmlDocument easily.

Example to select <Customer> elements having child node <Age> and <Status> empty, then remove those selected elements :

 var nodes = xmlDocument.DocumentElement.SelectNodes("//Customer[Age = '' and Status = '']"); foreach (XmlElement node in nodes) { node.ParentNode.RemoveChild(node); } 

UPDATE :

It seems that you're the one that construct the XML. So i'd suggest to check if str3 and str4 are empty, and if they are remove corresponding <Customer> element :

 if(string.IsNullOrEmpty(str3) && string.IsNullOrEmpty(str4)) { element1.ParentNode.RemoveChild(element1); } 

I understand that you're creating a new file and adding each element after the validation. I think this should work for you:

XDocument input = XDocument.Load("customers.xml");
XDocument output = new XDocument();
output.Add(new XElement("Customers"));
IEnumerable<XElement> elements = input.Element("Customers").Elements("customer");
foreach (XElement el in elements)
{
    string age = el.Element("Age").Value;
    string status = el.Element("Status").Value;
    if (age != "" || status != "")
    {
        output.Element("Customers").Add(el);
    }
}
output.Save("customers.xml");

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