我有这种格式的plist:
<plist version="1.0">
<array>
<dict>
<key>Title</key>
<string>Chapters</string>
<key>Items</key>
<array>
<dict>
<key>Title</key>
<string>XYZ</string>
</dict>
<dict>
<key>Title</key>
<string>ABC</string>
</dict>
</array>
</dict>
<dict>
<key>Title</key>
<string>ChaptersONE</string>
<key>Items</key>
<array>
<dict>
<key>Title</key>
<string>ASDF</string>
</dict>
</array>
</dict>
</array>
我有一个包含String和List的Class Chapters类:
我需要这样: 章节包含XYZ和ABC等子主题列表...... ChaptersONE包含ASDF等子主题列表......
现在我尝试过这样:
XDocument doc = XDocument.Load(FileName);// plist file name
XElement plist = doc.Element("plist");
XElement array = plist.Element("array");
Chapters chapters = null;
String keyValue = String.Empty;
chapters.listOfItems = new List<Chapters>();
using (XmlReader reader = array.CreateReader())
{
reader.MoveToContent();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "dict")
{
chapters = new Chapters();
listOfItems.Add(chapters);
}
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 (highwayCode != null && reader.NodeType == XmlNodeType.Text || reader.NodeType == XmlNodeType.CDATA)
{
switch (keyValue)
{
case "Title":
chapters.Header = reader.Value;
break;
case "Items":
break;
default:
break;
}
}
}
}
}
}
但是我所有的主标题(像Chapters和ChaptersOne这样的标题)以及副主题只是分配给字符串,我在这里做错了什么?
如何解决这个问题?
修改 章节应包含XYZ和ABC等子主题列表...... ChaptersONE应包含ASDF等子主题列表......
答案 0 :(得分:1)
是的,有一种更简单的方法:
XDocument doc = XDocument.Load("input.xml");// plist file name
var chapters = (from d in doc.Root.Element("array").Elements("dict")
select new Chapter
{
Title = (string)d.Element("string"),
SubTitles = d.Element("array")
.Elements("dict")
.Elements("string")
.Select(s => (string)s)
.ToList()
}).ToList();
你没有展示你的课程,所以我认为它看起来像那样:
class Chapter
{
public string Title { get; set; }
public List<string> SubTitles { get; set; }
}