[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 732
  • Last Modified:

Removing unused elements from the XML

Dear all

i am working with VS 2010, C#
i created my XML and XSD then i created the class file.

after serializing the class to XML
i found something like this:

in my original XML

i have this tag:

<Status>
<StatusCode>Status Code (ex:0200)</StatusCode>
<Severity>Severity (Enum)</Severity>
<StatusDesc>Fawry Status Message Description</StatusDesc>
</Status>

if i didnt fill the elements of the tag then it appear like "<Status/>"

i want to remove it.

how can i remove unused elements.

thanks,
0
RamzyNEbeid
Asked:
RamzyNEbeid
2 Solutions
 
BeartlaoiCommented:
Here is a sample that may do what you need.
            System.Xml.XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml("<Doc><Status/></Doc>");
            XmlNodeList xList = xDoc.SelectNodes("//*");
            foreach (XmlNode xNode in xList)
            {
                string sName = xNode.Name;
                if (!(xNode is XmlElement))
                    continue;
                XmlElement xElement = (XmlElement)xNode;
                if (xElement.ChildNodes.Count > 0 || xElement.Attributes.Count > 0)
                    continue;
                if (xElement.InnerText.Length > 0)
                    continue;
                xElement.ParentNode.RemoveChild(xNode);
            }
            string sXml = xDoc.OuterXml;

Open in new window

0
 
Fernando SotoCommented:
Hi RamzyNEbeid;

The following code snippet will remove all nodes in the document that has no child elements, has no attributes and is empty from the xdoc object.

using System.Xml.Linq;

// Load the XML document into memory
var xdoc = XDocument.Load("Path-To-XML-File/Status.xml");

// Get a list of nodes to be removed from the document
var results = (from node in xdoc.Root.Descendants()
               where !node.HasElements && !node.HasAttributes && node.IsEmpty
               select node).ToList();

// Remove the node from the xdoc object.
results.ForEach( n => n.Remove());
// Save the modified document back to the file system
xdoc.Save("Path-To-XML-File/Status-Modified.xml");

Open in new window

0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now