C# - parsing an XML string

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

I am developing in Visual Studio .NET 2005. I am attempting to parse
an XML string by using the example given in the help files:

ms-help://MS.VSCC.v80/MS.MSDNQ­TR.v80.en/MS.MSDN.v80/MS.NETDE­VFX.v20.en/cpref/html/M_System­_Xml_XmlReader_Create_1_6b7628­9f.htm

namely,

string xmlData ="<item productID='124390'>" +
"<price>5.95</price>" +
"</item>";

// Create the XmlReader object.
XmlReader reader = XmlReader.Create(new StringReader(xmlData));

However, when I attempt to actually parse this string by

reader.ReadStartElement("item"­);
string productID = reader.GetAttribute("productID­");

I just get null for productID. Can anyone see what I am doing wrong?

Thanks,
Don
 
ReadStartElement(<Name>) verifies that the current node is a start element
with the specified name. However, it then advances to the next node.So after
executing the line

reader.ReadStartElement("item"­);

the current node is now <title>. Since this node does not have an attribute
names "productID", GetAttribute("productID") returns null.

To check whether you are on the desired node and retrieve the attribute, try
something like this:

while (reader.Read()) { // parses the source XML one
node at a time
if (reader.Name.Equals("item")) {
string productID = reader.GetAttribute("productID­");
}

....

}

It might make more sense to switch on reader.NodeType and then process each
node based on whether it's an element, text node, etc., at least for the
node types you care about.

while (reader.Read()) {
switch (reader.NodeType) {
case XmlNodeType.Element:
// find out the name and react appropriately
break;
// process other node types as necessary
}
}

Hope this helps.
--
Kai Brinkmann [MSFT]

Please do not send e-mail directly to this alias. This alias is for
newsgroup purposes only.
This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top