asd

How to create XML of this structure

I would 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 am 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 it falls for how to add the "attribute" when I create the "element"

0


source to share


1 answer


You can add an attribute like this

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

      

It will become

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

      


XElement

looks like

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



  • because of params

    you can specify any number of objects

  • because of object

    you can specify

-> XAttribute

(which is added to that specific node),

-> string

(which ends up in XText and appended to node),

-> IEnumerable

,

-> Any other object

converted to string

with ToString()

, which is then converted to XText

and then added tonode

-> if object

is is null

ignored

-> if it XNode

is added tonode

+1


source







All Articles