简体   繁体   中英

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?

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.

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. 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;
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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