Search code examples
c#xelement

How to create an XML of this structure


I'd like to create an xml structure like below:

<root>
    <element name= "text here 1">
        <child>asd</child>
        <child>asd</child>
    </element>
    <element name= "text here 2">
        <child>asd</child>
        <child>asd</child>
    </element>
</root>

I'm familiar with

XElement doc = XElement.Load(mainDirectory);
XElement newElem = new XElement("element", new XElement(child, ""), new XElement(child, ""));
doc.Add(newElem);
doc.Save(mainDirectory);

So I think this falls down on how to add the "attribute" when I am creating "element"


Solution

  • You can add an attribute like this

    new XElement("element",new XAttribute("attribute","value") ,
                 new XElement(child, ""), 
                 new XElement(child, ""));
    

    This would become

    <element attribute="value">
        <child/>
        <child/>
    </element>
    

    XElement is similar to

    public XElement(XName name,params object[] content)

    • due to params you can specify any number of objects

    • due to object you can specify

    ->XAttribute(which gets added to that particular node),

    ->string(which gets wrapped in XText and gets added to node),

    ->IEnumerable,

    ->Any other object is converted to string using ToString() which is then converted to XText and then gets added to the node

    ->if object is null it is ignored

    ->if it is XNode,gets added to the node