如何在Windows 8平台中读取特定的xml元素

时间:2014-02-01 15:23:44

标签: c# xml linq

我有一个这种类型的xml文件

<HolyQuran TranslationID="103" Writer="Maulana Mohammad Ali" Language="English" LanguageIsoCode="eng" Direction="ltr">
<Chapter ChapterID="1" ChapterName="The Opening">
    <Verse VerseID="1"><![CDATA[In the name of Allah, the Beneficent, the Merciful.]]></Verse>
    <Verse VerseID="2"><![CDATA[Praise be to Allah, the Lord of the worlds,]]></Verse>
    <Verse VerseID="3"><![CDATA[The Beneficent, the Merciful,]]></Verse>
    <Verse VerseID="4"><![CDATA[Master of the day of Requital.]]></Verse>
    <Verse VerseID="5"><![CDATA[Thee do we serve and Thee do we beseech for help.]]></Verse>
    <Verse VerseID="6"><![CDATA[Guide us on the right path,]]></Verse>
    <Verse VerseID="7"><![CDATA[The path of those upon whom Thou has bestowed favours, Not those upon whom wrath is brought down, nor those who go astray.]]></Verse>
</Chapter>

我想要的是阅读特定的Verse Cdata部分。例如,如果我将章节id和Verse id传递给函数,那么它必须返回特定的cdata内容

我尝试了这段代码

 public  string  getTranslation(int p1, int p2)
    {
        string translationPath = Path.Combine(Package.Current.InstalledLocation.Path, "Data/eglish-translation.xml");
        XDocument document = XDocument.Load(translationPath);
       var  value = (from r in document.Descendants("Chapter").Where
                                  (r => ((int)r.Attribute("ChapterID") == p1)&&(int)r.Attribute("VerseId") == p2))
                 select r.Element("Verse").Value).FirstOrDefault();


          return value;  
    }

但它返回null我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

VerseIdVerse元素的属性,而不是Chapter元素的属性。这是正确的查询:

var value = (from c in document.Descendants("Chapter")
             where (int)c.Attribute("ChapterID") == p1 
             from v in c.Elements("Verse")
             where (int)v.Attribute("VerseID") == p2
             select (string)v).FirstOrDefault();

或者使用lambda语法:

var value = document.Descendants("Chapter")
                    .Where(c => (int)c.Attribute("ChapterID") == p1)
                    .SelectMany(c => c.Elements("Verse"))
                    .Where(v => (int)v.Attribute("VerseID") == p2)
                    .Select(v => (string)v)
                    .FirstOrDefault();

旁注 - 如果HolyQuran是xml文件的根元素,那么最好查询章节document.Root.Elements()document.Root.Elements("Chapter"),以避免遍历整个树的后代。

您也可以使用xpath:

var xpath = 
   String.Format("//Chapter[@ChapterID='{0}']/Verse[@VerseID='{1}']", p1, p2);
var value = (string)document.XPathSelectElement(xpath);