2014-10-27 49 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