Create xml format c# [closed]

2019-09-02 15:51发布

问题:

I want to make xml format like this in 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>

How do i form like this please help me

回答1:

You could use following code:

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


回答2:

Best way to achieve this is XMLSerialization. Create a property class as mentioned below and assign values to it :

[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; }
}

Now create an XML as mentioned below :

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

How to assign values and generate XML using method SerializeXML:

// 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);


回答3:

Check this article 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");

For other ways how to build xml in code check the following answers What is the best way to build XML in C# code