Reputation: 829
I have a xml file with this structure. The node "settings" is repeated only 1 time. The node "Reminders" can appear + 1 time.
<?xml version="1.0" encoding="utf-8"?>
<!--Name App-->
<AllSettings>
<Settings>
<tax1>21</tax1>
<tax2>0</tax2>
</Settings>
<Reminders>
<Name>s8</Name>
<Title>xxxxx</Title>
<Content>xxxxxxxxx</Content>
<BeginTime>09/11/2012 10:00:00</BeginTime>
</Reminders>
<Reminders>
<Name>s2</Name>
<Title>zzzzzzzzz</Title>
<Content>zzzzzzzzzzz</Content>
<BeginTime>07/11/2012 13:00:00</BeginTime>
</Reminders>
</AllSettings>
I can read data in "settings" node using the bottom code. But how I can read the data from each node "reminders"?
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile(myXmlFile, FileMode.Open);
isoFileStream.Position = 0;
XmlReader xmlReader;
xmlReader = XmlReader.Create(isoFileStream);
xmlReader.MoveToContent();
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Settings"
{
while (xmlReader.NodeType != XmlNodeType.EndElement)
{
xmlReader.Read();
if (xmlReader.Name == "tax1")
{
_tax1 = xmlReader.ReadElementContentAsString();
}
else if (xmlReader.Name == "tax2")
{
_tax2 = xmlReader.ReadElementContentAsString();
}
} // end while
}
else if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Reminders")
{
// ????
}
} // end while
Upvotes: 1
Views: 997
Reputation: 15794
Load it into an XDocument
and query using LINQ to XML.
var isoFileStream = myIsolatedStorage.OpenFile(myXmlFile, FileMode.Open);
isoFileStream.Position = 0;
var xdoc = XDocument.Load(isoFileStream);
var reminderNodes = from n in xdoc.Descendants("Reminders") select n;
foreach (var n in reminderNodes)
{
ProcessReminder(n);
}
void ProcessReminder(XElement node)
{
// do something... for now I'll just output to console.
Console.WriteLine("Name: {0}", n.Element("Name").Value);
Console.WriteLine("Title: {0}", n.Element("Title").Value);
Console.WriteLine("BeginTime: {0}", n.Element("BeginTime").Value);
Console.WriteLine();
}
Upvotes: 1
Reputation: 116168
Using Linq2Xml is much more easier
var xDoc = XDocument.Load(filename);
var reminders = xDoc.Descendants("Reminders")
.Select(r => new
{
Name = (string)r.Element("Name"),
Title = (string)r.Element("Title"),
Content = (string)r.Element("Content"),
BeginTime = (DateTime)r.Element("BeginTime"),
})
.ToList();
var firstTitle = reminders[0].Title;
or
var remDicts = xDoc.Descendants("Reminders")
.Select(r => r.Elements().ToDictionary(e => e.Name.LocalName, e => e.Value))
.ToList();
var firstTitle = remDicts[0]["Title"];
Upvotes: 2
Reputation: 1894
I would suggest to use xsd.exe tool to generate .XSD from XM and C# class from .XSD, and after that, just use LINQ syntax to interrogate.
This might help or this search
Upvotes: 0
Reputation: 887
I would recommend using XmlNode.Value instead of getting data from the XmlReader.
Upvotes: 0