I have below XML format to Create by XElement class
In Which you can see I have two parent node Service and Catalog. Now when I read from source below is code snippet
XElement rootElement = new XElement("Catalog", new XElement("Service"));//Create a root Element
foreach (....)// Logic for multiple product element
XElement productElement = new XElement("Product", new XAttribute("name", Obj.Product));//Read the Product
XElement variantElement = new XElement("Variant", new XAttribute("name",Obj.Variant));//Read variant
XElement skuElement = new XElement("SKU", new XAttribute("name", Obj.SKU));//Read SKU
productElement.Add(variantElement, skuElement);//Add varaint and skuvariant to product
rootElement.Add(productElement);//Add product to root element
But the Output is not expected,below is the output
You can see the second parent node appears as closure at the beginning. I know this line is creating the issue
XElement rootElement = new XElement("Catalog", new XElement("Service"));
but I need two root elements? What is the solution? How can i create?
Please help.
The
Service
element will always be empty because you never actually add anything to it, you just create it. You add your products to theCatalog
element instead of adding them to theService
element.Also, calling these "roots" isn't correct terminology as a valid XML document can only have one root (so in this case the only root element is
Catalog
).Here's the code:
The main changes are
I call it like this:
Here's the resulting XML:
Another clarification - in this case
Service
is not a root element (even though it's the only child ofCatalog
in this case).