2017-08-16 57 views
0

我想創建嵌套的XML,這樣的結果會是這樣的:如何在C#中嵌套的XML

<?xml version=\"1.0\" encoding=\"UTF-8\"?><TASKLOADLOG> 
<PERSON> 
<EMAIL>data</EMAIL><LOADED>OK</LOADED><LOADERROR>ABC</LOADERROR> 
</PERSON> 
<PERSON> 
<EMAIL>data</EMAIL><LOADED>OK</LOADED><LOADERROR>ABC</LOADERROR> 
</PERSON> 
<PERSON> 
<EMAIL>data</EMAIL><LOADED>OK</LOADED><LOADERROR>ABC</LOADERROR> 
</PERSON> 
</TASKLOADLOG>" 

我寫了下面的代碼,並墜毀在一個循環

XmlDocument XmlResponse = new XmlDocument(); 
XmlDeclaration xDeclare = XmlResponse.CreateXmlDeclaration("1.0", "UTF-8", null); 
XmlElement documentRoot = XmlResponse.DocumentElement; 
XmlResponse.InsertBefore(xDeclare, documentRoot); 
XmlElement el = (XmlElement)XmlResponse.AppendChild(XmlResponse.CreateElement("TASKLOADLOG")); 

List<XmlElement> ls = new List<XmlElement>(); 
for (int i = 0; i < 3; i++) 
{ 
    ls[i].AppendChild(XmlResponse.CreateElement("EMAIL")).InnerText = "data"; 
    ls[i].AppendChild(XmlResponse.CreateElement("LOADED")).InnerText = "OK"; 
    ls[i].AppendChild(XmlResponse.CreateElement("LOADERROR")).InnerText = "ABC"; 
} 

MessageBox.Show(XmlResponse.OuterXml); 

我不現在如何定義PERSON我需要寫什麼來修復我的代碼?

回答

0

問題很簡單,你不是在創建PERSON節點。電子郵件,Loaded和LoadError應該是Person節點的子節點。

編輯:

只是讓你知道,你甚至可以使用類的序列爲您試圖生成XML。

例如:

[Serializable] 
public class Person 
{ 
    [XmlAttribute] 
    public string Email { get; set; } 
    public string Loaded { get; set; } 
    public string LoadError{ get; set; } 
} 

Person p = new Person 
{ 
    Email = "abc", 
    Loaded = "abc"; 
    LoadError = "abc" 
}; 
new XmlSerializer(typeof(Person)).Serialize(Console.Out, Person); 
-1

您的代碼崩潰,因爲你是你的引用列表的第一個指數LS當列表爲空。

這樣創建您的文檔:

var doc = XDocument(new XElement("TASKLOADLOG")); 

for (int i = 0; i < 3; i++) 
    doc.Root.AppendChild(new XElement("PERSON", 
      new XElement("EMAIL", "data"), 
      new XElement("LOADED", "OK"), 
      new XElement("LOADERROR", "ABC") 
    ))); 
} 
+0

你應該解釋該代碼與OP代碼的區別。 – Enigmativity

0

感謝有關快速回答

我寫以下代碼,並得到了在XmlResponse.Root.AppendChild錯誤:

XmlDocument XmlResponse = new XmlDocument(); 
XmlDeclaration xDeclare = XmlResponse.CreateXmlDeclaration("1.0", "UTF-8", null); 
XmlElement documentRoot = XmlResponse.DocumentElement; 
XmlResponse.InsertBefore(xDeclare, documentRoot); 
XmlElement el = (XmlElement)XmlResponse.AppendChild(XmlResponse.CreateElement("TASKLOADLOG")); 

//List<XmlElement> ls = new List<XmlElement>(); 
for (int i = 0; i < 3; i++) 
{ 
    XmlResponse.Root.AppendChild(new XElement("PERSON", 
      new XElement("EMAIL", "data"), 
      new XElement("LOADED", "OK"), 
      new XElement("LOADERROR", "ABC") 
    ))); 
} 



MessageBox.Show(XmlResponse.OuterXml);