Newbee on XML - Needs some little help

  • Thread starter Thread starter VC
  • Start date Start date
V

VC

Sorry. Dont know if this is the right forum. I'm a newbee on XML and I
facing a problem

My XML string:

<resposta>
<totalSetor>78</totalSetor>
<totalAgencia>125</totalAgencia>
<senhas>
<item id=1>
<codigo>1</codigo>
<descricao>setor cc</descricao>
</item>
<item id=2>
<codigo>2</codigo>
<descricao>setor poup</descricao>
</item>
</senhas>
</resposta>

I'm using the following code to read the xml elements.

Console.Write(String.Format("totalSetor = {0}{1}",
xml.GetElementsByTagName("totalSetor").Item(0).InnerText,
Environment.NewLine));

Console.Write(String.Format("totalAgencia = {0}{1}",
xml.GetElementsByTagName("totalAgencia").Item(0).InnerText,
Environment.NewLine);

Til here, it's ok. But I'm stuck on how to read 'senhas' nodes and its
inner elements. Could someone give me some sample or points me to a
good tutorial?

Thanks in advance
 
Hi Pete

I'll check LINQ API. thank you very much.

VC said:
[...]
I'm using the following code to read the xml elements.
Console.Write(String.Format("totalSetor = {0}{1}",
xml.GetElementsByTagName("totalSetor").Item(0).InnerText,
Environment.NewLine));
Console.Write(String.Format("totalAgencia = {0}{1}",
xml.GetElementsByTagName("totalAgencia").Item(0).InnerText,
Environment.NewLine);
Til here, it's ok. But I'm stuck on how to read 'senhas' nodes and its
inner elements. Could someone give me some sample or points me to a
good tutorial?

You read those nodes the same way you read the other nodes.  The
GetElementsByTagName() method gets all descendants, not just immediate
children.

Alternatively, you can read directly from the "senhas" node, either by
using one of the XPath-friendly Select…() methods, enumerating the
ChildNodes collection, or using the indexer (passing it the name of the
child node you want to read from the "senhas" node).

Note that MSDN recommends the Select…() methods even for XmlDocument
instead of the GetElementsByTagName() method, right there in the docs
for the GetElementsByTagName() method.

You'll probably want to factor the code for handling those nodes out
into its own method to make the code easier to manage.

Also, you may want to look at the System.Xml.Linq namespace.  Even if
you're not actually using LINQ, it is IMHO a simpler API to use, and of
course it is designed to work very well with LINQ.

Pete
 
Back
Top