簡體   English   中英

如何使用XDocument添加元素及其屬性

[英]How to add element along with its attributes using XDocument

我可以使用XDocument通過添加元素

new XElement("elementName", "elementText");

並通過添加屬性

new XAttribute("attributeName", "attributeValue");

但是當我使用以下代碼

XDocument doc =
  new XDocument(
      new XElement("Address", new XAttribute("name", "sample"))
  );

沒有為“地址”元素添加任何文本。如何同時添加元素和屬性?

您可以將string作為另一個XElement構造函數參數傳遞,並將其作為元素內容放置:

XDocument doc =
    new XDocument(
        new XElement("Address",
            new XAttribute("name", "sample"),
            "elementText"
        )
    );

現在調用doc.ToString()給出<Address name="sample">elementText</Address>

只是讓您知道:它也可以使用XText類來完成,但是我認為使用純string更方便:

XDocument doc =
    new XDocument(
        new XElement("Address",
            new XAttribute("name", "sample"),
            new XText("elementText")
        )
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM