繁体   English   中英

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

[英]how to read a specific xml element in windows 8 platform

我有这种类型的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部分。 例如,如果我将Chapter 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我在这里做错了什么?

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM