2014-10-27 69 views
-2

对不起,我对XML API不太好。我将如何生成以下格式的XML文件并写入它?如何生成并写入此格式的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"); 
+0

让我们来看看你到目前为止有多远? – musefan 2014-10-27 16:37:17

+0

发布你的最佳尝试,让我们知道问题是什么。 – nvoigt 2014-10-27 16:37:27

+0

[在C#代码中构建XML的最佳方式是什么?](http://stackoverflow.com/questions/284324/what-is-the-best-way-to-build-xml-in-c -sharp-code) – 2014-10-27 16:56:50

回答

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

Loop;

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

唯一的是我该如何在此代码中调用CreateRow正确的次数? – user2471435 2014-10-27 18:20:55

+0

编辑答案。 – 2014-10-27 18:24:45

+0

唯一的问题 - 我不在控制台应用程序中。我将如何将它设置为新的XElement(“ROOT”,xml); – user2471435 2014-10-27 18:37:10