如何生成和编写这种格式的XML文件

本文关键字:格式 XML 文件 何生成 | 更新日期: 2023-09-27 18:27:56

对不起,我不擅长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");

如何生成和编写这种格式的XML文件

更简单的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));