Conditional XElement Content, XElement or XAttribute
I'm building XML based on some data pulled from a database, and thought to try building the XML with LINQ2XML. The data is coming from a few different places, so I've been building the XML by sections, based on what I have populated in DataTable objects.
Using the XElements and XAttributes, I can get one or the other, but I was wondering if anyone had insight in how to make the determination of whether to use XElement or XAttribute at the point where the XML is being built.
Here's a section from the XML building code with the XAttribute hard-coded (VB.NET):
...
New XElement("ParentNode",
New XElement("ChildNode",New XAttribute(XNamespace.Xmlns + "nil", "true"))
)
...
Here's an example of what I'm using throughout the XML building process to build child nodes where necessary:
...
New XElement("ParentNode",
From db 开发者_运维百科as DataRow in dtTable.Rows _
Order By db("Field") _
Select New XElement("ChildNode",
New XElement("ChildID",db("ValueToParse"))
)
)
...
So it's in that LINQ query that I need to determine if ValueToParse, for example, has a valid value (non-empty). If it does, then I can add the node and it's value. If it DOES NOT, I need to add that named node, but with an attribute of 'xsi:nil="true"'
The caveats are that that there are some descendants which repeat over different parents (for example, there's an AddressDetails section which contains AddressDetail elements. These AddressDetail elements can contain 0 or 1 Contacts groups of Contact elements, so adding a node to the Contacts node isn't a straightforward option as it would be if there was only ONE Contacts element).
I don't usually USE LINQ, but it SEEMED like a good idea at the time XD
Thanks, Chris
Sorry for my basic =) but i hope you will get the main idea.
New XElement("ParentNode",
From db as DataRow in dtTable.Rows _
Order By db("Field") _
Select New XElement("ChildNode",
db("ValueToParse") != null ? (object)new XElement("ChildID", db("ValueToParse")) :
(object)new XAttribute("xsi:nil", "true"))
)
)
精彩评论