我正在尝试读取XML格式的一些数据,这是我的Windows 8手机应用程序中的CDATA。以下是数据样本:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE HolyQuran [
<!ATTLIST HolyQuran TranslationID CDATA #REQUIRED>
<!ATTLIST HolyQuran Writer CDATA #REQUIRED>
<!ATTLIST HolyQuran Language CDATA #REQUIRED>
<!ATTLIST HolyQuran LanguageIsoCode CDATA #REQUIRED>
<!ATTLIST HolyQuran Direction (rtl|ltr) #REQUIRED>
<!ELEMENT HolyQuran (Chapter+)>
<!ATTLIST Chapter ChapterID CDATA #REQUIRED>
<!ATTLIST Chapter ChapterName CDATA #REQUIRED>
<!ELEMENT Chapter (Verse+)>
<!ATTLIST Verse VerseID CDATA #REQUIRED>
<!ELEMENT Verse (#PCDATA)>
]>
<!-- This SQL Query Generated at 22 November 2013 01:44 (UTC) from
www.qurandatabase.org -->
<HolyQuran TranslationID="59" Writer="Yusuf Ali" Language="English"
LanguageIsoCode="eng" Direction="ltr">
<Chapter ChapterID="1" ChapterName="The Opening">
<Verse VerseID="1"><![CDATA[In the name of Allah, Most Gracious, Most
Merciful.]]></Verse>
<Verse VerseID="2"><![CDATA[Praise be to Allah, the Cherisher and Sustainer
of the worlds;]]></Verse>
<Verse VerseID="3"><![CDATA[Most Gracious, Most Merciful;]]></Verse>
<Verse VerseID="4"><![CDATA[Master of the Day of Judgment.]]></Verse>
<Verse VerseID="5"><![CDATA[Thee do we worship, and Thine aid we seek.
]]></Verse>
<Verse VerseID="6"><![CDATA[Show us the straight way,]]></Verse>
<Verse VerseID="7"><![CDATA[The way of those on whom Thou hast bestowed Thy
Grace, those whose (portion) is not wrath, and who go
not astray.]]></Verse>
</Chapter>
</HolyQuran>
我想获得一个数据结构,其中包含ChapterName,ChapterID和所有经文内容的列表及其对应的VerseID。请注意,根据诗歌内容,我的意思是CDATA。我需要使用XDocument,但我无法弄清楚如何解析这个复杂的XML。
我将非常感谢任何帮助!
谢谢!
答案 0 :(得分:0)
首先,您需要Chapter
和Verse
类:
public class Chapter
{
public int Id { get; set; }
public string Name { get; set; }
public List<Verse> Verses { get; set;}
}
public class Verse
{
public int Id { get; set; }
public string Contents { get; set; }
public static Verse FromXElement(XElement element)
{
return new Verse { Id = (int)element.Attribute("VerseID"),
Contents = element.Value };
}
}
然后它更简单:
XDocument doc = //get your document
XElement chapter = doc.Root.Element("Chapter");
Chapter result = new Chapter { Id = (int)chapter.Attribute("ChapterId"),
Name = (string)chapter.Attribute("ChapterName"),
Verses = chapter.Elements().Select(Verse.FromXElement).ToList() }
(我使用FromXElement
方法,因为它看起来更整洁,如果你愿意,你可以内联它。