简体   繁体   English

如何从XML文件检索所有数据?

[英]How do I retrieve all data from an XML file?

I used this code for retrieving specific value from the XML file.Now i want to retrieve all the data which are present in the XML file .Can anybody help me to find out the solution? 我使用此代码从XML文件中检索特定值。现在,我想检索XML文件中存在的所有数据。有人可以帮助我找出解决方案吗?

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 duc.Root.Elements("Serial")
    where Date.Attribute("No").Value=="1"
    from Current in Date.Elements("Current")
    select new {
        NarratedBy=Current.Attribute("NarratedBy").Value,
        value=Current.Attribute("Date").Value
    };

foreach(var Date in query) {
    System.Diagnostics.Debug.WriteLine("{0}\t{1}", Date.NarratedBy, Date.value);
}

You already have whole XML document loaded into duc variable. 您已经将整个XML文档加载到duc变量中。

That line is responsible for that: 该行负责:

System.Xml.Linq.XDocument duc = System.Xml.Linq.XDocument.Parse(xmlDoc.GetXml());

那么您只需将您的XDocument详细信息检索到例如带有XDocument扩展名ToString()string变量中

You have all data already: 您已经拥有所有数据:

xmlDoc = await XmlDocument.LoadFromFileAsync(xmlFile); // data loadded
System.Xml.Linq.XDocument duc = System.Xml.Linq.XDocument.Parse(xmlDoc.GetXml()); // data parsed

=================== ===================

Here is a sample code how you may do it. 这是一个示例代码,您可以如何做。 It is fully functional (using local string xml instead of your file) so you may run it. 它具有全部功能(使用本地字符串xml而不是文件),因此您可以运行它。 I added only three attributes but you may add as many as you want. 我仅添加了三个属性,但您可以根据需要添加任意多个属性。

class Program {
static void Main(string[] args) {
// this is a sample string. Use your file instead
string s = "<catalog>" +
"<book id=\"bk101\" author=\"Gambardella, Matthew\" title=\"XML Developer's Guide\" genre=\"Computer\"/>" +
"<book id=\"bk102\" author=\"Ralls, Kim\" title=\"Midnight Rain\" genre=\"Fantasy\"/>" +
"</catalog>";

XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(s); // here we load data
// here we get attributes. I have three, you will add three more. Also you may want to use string array instead of variables
            foreach (XmlNode task in xdoc.DocumentElement.ChildNodes)
{
                string author = task.Attributes["author"].InnerText;
                string title = task.Attributes["title"].InnerText;
                string genre = task.Attributes["genre"].InnerText;
            }
        }
    }

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

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