-5
我試圖解析XML,並分配給對象:通過移動到每個節點類型解析XML文檔
XML文件:
<plist version="1.0">
<array>
<dict>
<key>SubTitle</key>
<array>
<dict>
<key>IDs</key>
<array>
<string>CD1</string>
<string>CD2</string>
<string>CD3</string>
</array>
<key>Title</key>
<string>Data One</string>
<key>ABC</key>
<string></string>
<key>XYZ</key>
<string></string>
<key>HasLessons</key>
<true/>
</dict>
<dict>
<key>IDs</key>
<array>
<string>DDC1</string>
<string>DDC2</string>
<string>DDC3</string>
</array>
<key>Title</key>
<string>Data Two</string>
<key>ABC</key>
<string></string>
<key>XYZ</key>
<string></string>
<key>HasLessons</key>
<true/>
</dict>
</array>
<key>MainTitle</key>
<string>Collection of Data</string>
</dict>
</array>
</plist>
我試圖解析如下:
XDocument doc = XDocument.Load(FileName);
XElement plist = doc.Element("plist");
XElement array = plist.Element("array");
int topicID = 0;
Topic topic = new Topic();
String keyValue = String.Empty;
topicCollection = new List<Topic>();
using (XmlReader reader = array.CreateReader())
{
reader.MoveToContent();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "dict")
{
topicID++;
topic = new Topic();
topic.TopicID = topicID;
topicCollection.Add(topic);
}
else if (reader.Name == "key")
{
if (!reader.Read())
{
break;
}
else if (reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
{
keyValue = reader.Value;
}
}
else if (reader.Name == "string")
{
if (!reader.Read())
{
break;
}
else if (topic != null && reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
{
switch (keyValue)
{
case "Title":
topic.SubTitle = reader.Value;
break;
case "IDs":
topic.FileNames.Add(reader.Value);
break;
case "ABC":
topic.ABC = int.Parse(reader.Value);
break;
case "XYZ":
topic.XYZ = reader.Value;
break;
case "MainTitle":
topic.MainTitle = reader.Value;
break;
default:
break;
}
}
}
}
else if (reader.NodeType == XmlNodeType.EndElement)
{
if (reader.Name == "dict" && topic != null)
{
}
}
}
}
我在這裏做錯了什麼? 我試圖在第一個屏幕中顯示所有主標題,然後點擊每個主標題顯示字幕列表並點擊每個字幕顯示的ID標題列表。
另請參閱http://stackoverflow.com/questions/22146447/linq-to-xml-with-nested-dictionary-and-array和http://stackoverflow.com/questions/22156794/xml-parsing-with -dictionarystring-listmyobject –
只是想知道 - 爲什麼你正在創建XDocument,但使用XmlReader?甚至更有趣的問題 - 爲什麼你不使用你昨天問的問題解決方案http://stackoverflow.com/questions/22156794/xml-parsing-with-dictionarystring-listmyobject –
@SergeyBerezovskiy我很抱歉地說,但是當我試圖打印的值不打印任何東西,而且我想這是我試圖達到結果 – user3114009