maha
maha

Reputation: 67

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

Upvotes: 0

Views: 187

Answers (3)

QArea
QArea

Reputation: 4981

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

Upvotes: 0

roybalderama
roybalderama

Reputation: 1640

then you can just retrieve your XDocument details for example into a string variable with an XDocument extension ToString()

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

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

Upvotes: 1

Related Questions