2014-03-26 16 views
1

我要讓XML格式像這樣在C#中的XML格式創建C#

<?xml version='1.0' encoding='us-ascii'?> 
<root> 
<key value="22.wav"> 
<Index>1</Index> 
<Index>20</Index> 
<Index>21</Index> 
</key> 
<key value="EFG.wav"> 
<Index>5</Index> 
<Index>22</Index> 
</key> 
</root> 

我如何形成這樣的請幫我

+0

看看這個。可能有幫助。 http://stackoverflow.com/questions/15083727/how-to-create-xml-in-c-sharp –

回答

1

你可以使用下面的代碼:

XDocument doc = new XDocument(new XDeclaration("1.0", "us-ascii", null), 
     new XElement("root", 
      new XElement("key", new XAttribute("value", "22.wav"), 
       new XElement("Index", 1), 
       new XElement("Index", 20), 
       new XElement("Index", 21)), 
      new XElement("key", new XAttribute("value", "EFG.wav"), 
       new XElement("Index", 5), 
       new XElement("Index", 22)))); 
    doc.Save(fileName); 
+0

我如何動態 – munisamy

+0

@munisamy:使用相同的方法。首先,創建靜態部分(聲明和根元素),然後動態創建和添加元素(使用XElement.Add方法添加子元素) –

0

檢查這篇文章XmlDocument fluent interface

XmlOutput xo = new XmlOutput() 
       .XmlDeclaration() 
       .Node("root").Within() 
        .Node("key").Attribute("value", "22.wav").Within() 
         .Node("Index").InnerText("1") 
         .Node("Index").InnerText("20") 
         .Node("Index").InnerText("21").EndWithin() 
        .Node("key").Attribute("value", "EFG.wav").Within() 
         .Node("Index").InnerText("2") 
         .Node("Index").InnerText("22"); 

string s = xo.GetOuterXml(); 
//or 
xo.GetXmlDocument().Save("filename.xml"); 

的其他方法如何在代碼構建XML檢查下列答案實現這一目標是XMLSerializationWhat is the best way to build XML in C# code

1

的最佳方式。創建一個屬性類下面提到和值分配給它:

[Serializable] 
[XmlRoot("root")] 
public class RootClass 
{ 
    [XmlElement("key")] 
    public List<KeyClass> key { get; set; } 
} 

[Serializable] 
[XmlType("key")] 
public class KeyClass 
{ 
    [XmlElementAttribute("value")] 
    public string KeyValue { get; set; } 

    [XmlElement("Index")] 
    public List<int> index { get; set; } 
} 

現在創建一個XML如下所述:

static public void SerializeXML(RootClass details) 
{ 
    XmlSerializer serializer = new XmlSerializer(typeof(RootClass)); 
    using (TextWriter writer = new StreamWriter(@"C:\Xml.xml")) 
    { 
     serializer.Serialize(writer, details); 
    } 
} 

如何分配值,並使用方法SerializeXML生成XML:

// Create a New Instance of the Class 
var keyDetails = new RootClass(); 
keyDetails.key = new List<KeyClass>(); 

// Assign values to the Key property 
keyDetails.key.Add(new KeyClass 
         { 
          KeyValue = "22.wav", 
          index = new List<int> { 1, 2, 3} 
         }); 

keyDetails.key.Add(new KeyClass 
{ 
    KeyValue = "EFG.wav", 
    index = new List<int> { 5 , 22 } 
}); 

// Generate XML 
SerializeXML(keyDetails); 
+0

如何動態添加KeyValue和索引。 – munisamy

+0

你是什麼意思動態?您始終可以從控制值中動態添加KetValue。 – SpiderCode