Groups | Blog | Home
all groups > dotnet xml > may 2004 >

dotnet xml : Looping through attributes


chawes7420 NO[at]SPAM aol.com
5/7/2004 1:16:37 PM
I need a sample that shows how can loop through the
attributes and display the data.(.net / c#)

<?xml version="1.0" encoding="UTF-8"?>
<riders>
<rider>
<prename id=>Lance</prename>
<surname>Armstrong</surname>
</rider>
<rider>
<prename>Roberto</prename>
<surname>Heras</surname>
</rider>
<rider>
<prename>George</prename>
<surname>Hincapie</surname>
</rider>
<Position>
<Element Operation="insert" remark="Test Add Remark1"/>
<Element Operation="insert" remark="Test Add Remark2"/>
</Position>
</riders>

Code:

XmlElement child2 = child.SelectSingleNode("ns:Element");
oper1 = child2.GetAttribute("Operation");

int i;
for ( i = 1; i < 3; i++)
{
if (oper1 == "insert")
{
remk = child2.GetAttribute("Child");
MessageBox.Show(remk);
}
}

This works fine but it only give me the first remark, it never goes to
the second remark. Also I have hard coded "< 3", but I don't know the
Martin Honnen
5/9/2004 12:30:01 PM


[quoted text, click to view]

Here is an example that loops through all <Element> elements that have
the id attribute Operation set to "insert" and then outputs the value of
the attribute named remark:

using System;
using System.Xml;

public class Test20040509 {
public static void Main (string[] args) {
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(@"test20040509.xml");
XmlNodeList nodeList = xmlDocument.SelectNodes(
"/riders/Position/Element[@Operation = 'insert']");
foreach (XmlNode node in nodeList) {
XmlElement element = node as XmlElement;
if (element != null) {
Console.WriteLine(element.GetAttribute("remark"));
}
}
}
}
--

Martin Honnen
http://JavaScript.FAQTs.com/
cheryl hawes
5/10/2004 12:23:26 PM
XmlNodeList nodeList = xmlDocument.SelectNodes(
"/riders/Position/Element[@Operation = 'insert']")

Would the above nodeList change if my Xml looked as following:


<?xml version="1.0" encoding="UTF-8"?>
[quoted text, click to view]




*** Sent via Developersdex http://www.developersdex.com ***
Kirk Allen Evans [MSFT]
5/11/2004 9:13:25 AM
Yes. The XPath expression included in your sample code looks for the very
first element in the document calles "riders", having a child element
"Position", having a child element named "Element", that has an attribute
named "Operation" with a value of "insert". If all of these conditions are
not met, then nothing will be matched... hence nothing is returned. Your
first element is now "UpdateRQ", so the XPath expression will not match
anything in your structure. Add the UpdateRQ element into your XPath
statement:

XmlNodeList nodeList =
xmlDocument.SelectNodes("/UpdateRQ/riders/Position/Element[@Operation =
'insert']")

--
Kirk Allen Evans
blogs.msdn.com/kaevans

-- This posting is provided "AS IS" with no warranties, and confers no
rights.

[quoted text, click to view]

AddThis Social Bookmark Button