如何生成和编写此格式的XML文件?

时间:2014-10-27 16:35:23

标签: c# xml

对不起,我对XML API不太满意。如何生成以下格式的XML文件并编写它?

<?xml version="1.0" encoding="utf-8" ?> 

<ROOT>
  <LOC ID="*">
    <ROW ID = "1" CD = "US" DESC = "United States" ISACTIVE="1" ORDER="1"/>
    <ROW ID = "2" CD = "CA" DESC = "Canada" ISACTIVE="1" ORDER="2"/>
    <ROW ID = "3" CD = "XX" DESC = "Others" ISACTIVE="1" ORDER="3"/>
  </LOC>
</ROOT>

这是我最好的第一次尝试。硬编码的值必须由数据库中的值替换。我不知道如何迭代和创建多行元素。

XmlDocument xmlDoc = new XmlDocument();
XmlNode rootNode = xmlDoc.CreateElement("ROOT");
xmlDoc.AppendChild(rootNode);

XmlNode locNode = xmlDoc.CreateElement("LOC");
XmlAttribute attr = xmlDoc.CreateAttribute("ID");
attr.Value = "*";
rootNode.AppendChild(locNode);

XmlNode rowNode = xmlDoc.CreateElement("ROW");
XmlAttribute id = xmlDoc.CreateAttribute("CD");
id.Value = "1";
XmlAttribute cd = xmlDoc.CreateAttribute("CD");
cd.Value = "US";
XmlAttribute desc = xmlDoc.CreateAttribute("DESC");
desc.Value = "United States";
XmlAttribute active = xmlDoc.CreateAttribute("ISACTIVE");
active.Value = "1";
XmlAttribute order = xmlDoc.CreateAttribute("ORDER");
order.Value = "1";
rootNode.AppendChild(rowNode);

xmlDoc.Save("foo.xml");

1 个答案:

答案 0 :(得分:1)

更简单using System.Xml.Linq;

    ...
    var xml = new XElement("ROOT", 
        new XElement("LOC", new XAttribute("ID", "*"),
            CreateRow(1, "US", "United States", 1, 1),
            CreateRow(2, "CA", "Canada", 1, 2),
            CreateRow(3, "XX", "UOthers", 1, 3)));

    Console.WriteLine(xml);
}

static XElement CreateRow(int id, string cd, string desc, int isActive, int order)
{
    return new XElement("ROW",
        new XAttribute("ID", id),
        new XAttribute("CD", cd),
        new XAttribute("DESC", desc),
        new XAttribute("ISACTIVE", isActive),
        new XAttribute("ORDER", order));
}

循环;

var xml = new XElement("LOC", new XAttribute("ID", "*"));

for (var i = 1; i < 10; i++)
{
    xml.Add(CreateRow(i, "?", "?", 1, i));
}

Console.WriteLine(new XElement("ROOT", xml));