I am fairly new to XML and parsing it with C#. I am trying to parse an XML document that looks like this:
<Msg Version="1.0">
<ProgList>
<update sequence="41248" amount="3327" Lvl="1" Grp="1" />
<update sequence="41216" amount="5326" Lvl="2" Grp="1" />
<update sequence="41252" amount="7326" Lvl="3" Grp="1" />
</ProgList>
</Msg>
I'm trying to use XDocument and can't seem to parse out the three updates with the attributes.
However, if I create an XML document containing the same data in this form:
<Msg Version="1.0">
<ProgList>
<Level>
<seq>41248</seq>
<amount>3327</amount>
<Lvl>1</Lvl>
<Grp>1</Grp>
</Level>
<Level>
<seq>41216</seq>
<amount>5326</amount>
<Lvl>2</Lvl>
<Grp>1</Grp>
</Level>
<Level>
<seq>41252</seq>
<amount>7326</amount>
<Lvl>3</Lvl>
<Grp>1</Grp>
</Level>
</ProgList>
</Msg>
I can parse and iterate through the Level data using the following code:
String xmlText = String.Empty;
//String xml = String.Empty;
int begin = Data.IndexOf("<?xml");
int end = Data.IndexOf("</Msg") + 6;
try
{
//xml = Data.Substring(begin, end - begin);
}
catch { };
String xml =
@"<Msg Version='1.0'>
<ProgList>
<Level>
<seq>41248</seq>
<amount>3327</amount>
<Lvl>1</Lvl>
<Grp>1</Grp>
</Level>
<Level>
<seq>41216</seq>
<amount>5326</amount>
<Lvl>2</Lvl>
<Grp>1</Grp>
</Level>
<Level>
<seq>41252</seq>
<amount>7326</amount>
<Lvl>3</Lvl>
<Grp>1</Grp>
</Level>
</ProgList>
</Msg>";
try
{
XDocument xmlDoc = XDocument.Parse(xml);
var updates = from x in xmlDoc.Descendants("Level")
select new
{
seq = x.Descendants("seq").First().Value,
amt = x.Descendants( "amount" ).First().Value,
lvl = x.Descendants("Lvl").First().Value,
grp = x.Descendants("Grp").First().Value
};
foreach (var x in updates)
{
String output = String.Format("{0}SEQ: {1} AMT: {2} LVL: {3} GRP: {4}",
Environment.NewLine, x.seq, x.amt, x.lvl, x.grp);
}
How would I parse out the first XML document style?