【问题标题】:How to create an XML of this structure如何创建这种结构的 XML
【发布时间】:2012-12-05 22:41:39
【问题描述】:

我想创建一个如下所示的 xml 结构:

<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>

我很熟悉

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

所以我认为这取决于我在创建“元素”时如何添加“属性”

【问题讨论】:

  • 无效的 XML 你不能使 element = "text here 2"..
  • 谢谢大家!固定结构,忘了!

标签: c# xelement


【解决方案1】:

你可以像这样添加一个属性

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

这会变成

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

XElement 类似于

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

  • 由于params,您可以指定任意数量的对象

  • 由于object你可以指定

->XAttribute(被添加到特定节点),

->string(被 XText 包裹并添加到节点),

->IEnumerable,

->Any other object 使用ToString() 转换为string,然后转换为XText,然后添加到node

->如果 objectnull 则被忽略

->如果是XNode,则添加到node

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 1970-01-01
    • 2017-10-12
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    相关资源
    最近更新 更多