Excluding / Removing empty elements from XElement

W

wdudek

Does anyone know of any easy way to exclude / remove empty elements from an
XElement so that when I do xelement.Save("filename"); I won't have them? In
the short example to follow the second invoice section has two elements
(PONumber, SomeValue) with no data I would prefer not to create these at all.

C#

class Program
{

public struct InvoiceStruct
{
public int InvoiceNumber;
public int LineItems;
public string PONumber;
public int? SomeValue;
}



static void Main(string[] args)
{

InvoiceStruct [] invoices = new InvoiceStruct [2];

invoices[0].InvoiceNumber = 1;
invoices [0].LineItems = 5;
invoices[0].PONumber = "abc";
invoices[0].SomeValue = 4;

invoices[1].InvoiceNumber = 2;
invoices[1].LineItems = 10;




XElement xml = new XElement("Invoices",
from i in invoices
select new XElement("Invoice",
new XElement("InvoiceNumber",
i.InvoiceNumber),
new XElement("LineItems",
i.LineItems),
new XElement ("PONumber",
i.PONumber ),
new XElement ("SomeValue",
i.SomeValue )
)
);



xml.Save("c:\\temp\\test.xml");


Console.WriteLine("done");


Console.ReadKey();

}
}


Generated XML

<Invoices>
<Invoice>
<InvoiceNumber>1</InvoiceNumber>
<LineItems>5</LineItems>
<PONumber>abc</PONumber>
<SomeValue>4</SomeValue>
</Invoice>
<Invoice>
<InvoiceNumber>2</InvoiceNumber>
<LineItems>10</LineItems>
<PONumber />
<SomeValue />
</Invoice>
</Invoices>

Thanks Bill
 
W

wdudek

Thanks, I wasn't aware it would ignore the null elements. I managed to come
up with a differnt solution to the problem, which so far is working although
it seems like it could open me up to some unexpected problem. Also it didn't
involve changing any of the existing code that creates the xml, which is
substantial. The code follows, if anyone sees a problem with this please let
me know.

Thanks

Bill

List<XElement> remove = new List<XElement>();

foreach (XElement e in xml.DescendantsAndSelf())
{

if (e.Value == "" && !e.HasElements && !e.HasAttributes)
remove.Add(e);

}


foreach (XElement r in remove)
r.Remove();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top