簡體   English   中英

從xml文件中檢索元素

[英]Retrieve Element from xml file

我正在使用以下代碼來檢索和顯示XML文件中的所有值。

private async void Button_Click_1(object sender, RoutedEventArgs e)
{
     StorageFile xmlFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("Content1.xml");
     XmlDocument xmlDoc;
     xmlDoc = await XmlDocument.LoadFromFileAsync(xmlFile);                 
     System.Xml.Linq.XDocument duc = System.Xml.Linq.XDocument.Parse(xmlDoc.GetXml());

     //var query = from Date in xmlDoc.Root.Elements("Serial")
     var query = from Date in duc.Root.Elements("Serial")
                 where Date.Attribute("No").Value == "1"
                 from Current in Date.Elements("Current")
                 select new
                 {
                     value = Current.Attribute("EnglishDate").Value,
                     Arabic = Current.Attribute("ArabicDate").Value,
                     NarratedBy = Current.Attribute("Narrated").Value,
                     Content = Current.Attribute("HadithBody").Value,
                     TransmittedBy = Current.Attribute("RefferedBy").Value,
                     RefferedVerses = Current.Attribute("RefferedVerses").Value
                 };

     foreach (var Date in query)
     {
        xmlTextBlock.Text=String.Format("{0}\t{1}",Date.NarratedBy,Date.Value,Date.Arabic,Date.Content,Date.TransmittedBy,Date.RefferedVerses)+Environment+NewLine;
     }        
}

這是我的XML文件

<?xml version="1.0" encoding="utf-8" ?>
  <Hadith>
    <Serial No="1">
      <Current EnglishDate="22 January 2013"
               ArabicDate="10 Rabi-Ul-Awal 1434"
               Narrated="Narrated Hasan:"
               HadithBody="Knowledge is of two types.Firstly,knowledge perceived by the heart,and that is useful knowledge"
               RefferedBy="Transmitted by:"
               RefferedVerses="Darimi-Al-Timidhi-Hadith 270">
     </Current>
   </Serial>
 </Hadith>

此代碼未顯示所有值。 要顯示我在XMLfile中聲明的所有值,我該怎么做?

修改您的foreach循環代碼:

xmlTextBlock.Text= String.Empty;
foreach (var Date in query)
     {
        xmlTextBlock.Text += String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\n",
                     Date.NarratedBy,Date.Value,Date.Arabic,Date.Content,
                     Date.TransmittedBy,Date.RefferedVerses);
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM