[英]How to remove an element from an xml using Xdocument when we have multiple elements with same name but different attributes
[英]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.