简体   繁体   中英

How to remove null valued child nodes in Xml using c#

I have an XML Documnet consisting parent nodes and child nodes,

<?xml version='1.0' encoding='UTF-8'?> 
<response>   
   <system_timestamp>2016-10-21 13:40:28</system_timestamp>
   <response_data>   
    <status>Active</status>   
    <profile>     
     <first_name>John</first_name>
     <last_name>Abraham</last_name>
     <ship_to_address>        
      <address_1>null</address_1>      
      <address_2>null</address_2>  
      <city>null</city>      
      <state>null</state>   
      <postal_code>null</postal_code> 
     </ship_to_address>  
    </profile>
  </response_data>  
</response>

I am having few null valued child nodes like <address_1> and <address_2> . So, now how would I remove those null values of my child nodes. I tried

doc.Descendants().Where(e => string.IsNullOrEmpty(e.Value)).Remove();

But this is not working . And i am using this XmlDocument doc = new XmlDocument(); doc.LoadXml(_value); XmlDocument doc = new XmlDocument(); doc.LoadXml(_value);

code to parse xml document. Do we have any other methods to remove using XMLDocument instead of XElement.

e.Value isn't a null reference or an empty string - it's the string "null" because that's the value in your element.

You want:

doc.Descendants().Where(e => (string) e == "null").Remove();

When removing an item from a list you must removed from last item to first item otherwise the indexing gets screwed up and not all the items get removed. Try this

sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> nulls = doc.Descendants().Where(x => (string)x == "null").ToList();
            for (int i = nulls.Count - 1; i >= 0; i--)
            {
                nulls[i].Remove();
            }
        }
    }
}

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