How to create an XML of this structure

我的未来我决定 提交于 2019-12-13 21:14:09

问题


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"


回答1:


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



来源:https://stackoverflow.com/questions/13725426/how-to-create-an-xml-of-this-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!