2012-01-21 20 views
3

兩個屬性我要讓XML元素是這樣的:的xml在C#

<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</Atrybut> 

現在我這樣做的:

XmlNode xmlAtrybutNode = xmlDoc.CreateElement("ElementName "); 

_xmlAttr = xmlDoc.CreateAttribute("Type"); 
_xmlAttr.Value = "FirstAttribute"; 
xmlAtrybutNode.Attributes.Append(_xmlAttr); 

_xmlAttr = xmlDoc.CreateAttribute("Name"); 
_xmlAttr.Value = "SecondAttribute"; 
xmlAtrybutNode.Attributes.Append(_xmlAttr); 


xmlAtrybutNode.InnerText = !string.IsNullOrEmpty(Value) 
    ? SetTextLength(Name, ValueLength) 
    : string.Empty; 

值是在方法輸入變量。 有沒有可能以另一種方式做到這一點? 更高效? 我可以使用xmlWriter嗎?現在我正在使用xmlDocument。

+0

/en-us/library/system.xml.serialization.xmlserializer.aspx – yas4891

+0

你試圖生成什麼看起來相當破碎的XML。 –

+0

爲什麼相當破碎?我按照規範來做這件事。我有示例XML輸出,我必須產生該XML。 – ogrod87

回答

4

如何調整現有的代碼:

XmlElement el = xmlDoc.CreateElement("ElementName"); 
el.SetAttribute("Type", "FirstAttribute"); 
el.SetAttribute("Name", "SecondAttribute"); 
el.InnerText = ...; 

更多的想法:

  • 的XElement
  • XmlSerializer的(從一個類的實例)
+0

它的工作原理。謝謝;) – ogrod87

3

有關使用LINQ to XML是什麼如在這article。這可以非常優雅 - 它可以在一條線上完成。

XDocument doc = new XDocument(
     new XDeclaration("1.0", "utf-8", "yes"), 
     new XElement("element", 
      new XAttribute("attribute1", "val1"), 
      new XAttribute("attribute2", "val2"), 
     ) 
); 
4

如果您使用.NET 3.5(或更高版本),則可以使用LINQ to XML。確保System.Xml.Linq程序集已被引用,並且您的同名命名空間有一個using指令。

XDocument document = new XDocument(
    new XElement("ElementName", 
     new XAttribute("Type", "FirstAttribute"), 
     new XAttribute("Name", "SecondAttribute"), 
     value)); 

如果以後想在XDocument寫一個目標,你可以使用它的方法Save。對於調試,調用其ToString方法很有用,該方法返回其XML表示形式爲string

編輯:答覆意見:

如果您需要在上面創建成XmlDocument實例XDocument轉換,你可以使用類似的代碼如下:

XmlDocument xmlDocument = new XmlDocument(); 
using (XmlReader xmlReader = document.CreateReader()) 
    xmlDocument.Load(xmlReader); 
+0

我可以將此文檔作爲appendChild添加到xmlDocument嗎? – ogrod87

6

您可以使用LINQ到XML。 http://msdn.microsoft.com:

基本上

 XDocument doc = new XDocument(); 
     doc.Add(
      new XElement("ElementName", "Value", 
       new XAttribute("Type", "FirstAttribute"), 
       new XAttribute("Name", "SecondAttribute"))); 

會,如果你正試圖從序列化您的應用程序對象在`XmlSerializer`看看給這個XML文檔

<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</ElementName>