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
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