XML/C#: Read content if only if attribute is correct
Posted
by Zach
on Stack Overflow
See other posts from Stack Overflow
or by Zach
Published on 2010-03-16T08:35:23Z
Indexed on
2010/03/16
8:56 UTC
Read the original article
Hit count: 359
Hi Guys,
I have an XML file as follows, and I'm trying to read the content of the Name tag, only if the attribute of the Record tag is what I want. (continued below code)
The XML file is:
<?xml version="1.0" encoding="utf-8" ?>
<Database>
<Record Number="1">
<Name>John Doe</Name>
<Position>1</Position>
<HoursWorked>290</HoursWorked>
<LastMonthChecked>0310</LastMonthChecked>
</Record>
<Record Number="2">
<Name>Jane Doe</Name>
<Position>1</Position>
<HoursWorked>251</HoursWorked>
<LastMonthChecked>0310</LastMonthChecked>
</Record>
</Database>
This is the C# code I have so far:
public static string GetName(int EmployeeNumber)
{
XmlTextReader DataReader = new XmlTextReader("Database.xml");
DataReader.MoveToContent();
while (DataReader.Read())
{
if (DataReader.NodeType == XmlNodeType.Element
&& DataReader.HasAttributes && DataReader.Name == "Record")
{
DataReader.MoveToAttribute(EmployeeNumber);
DataReader.MoveToContent();
if (DataReader.NodeType == XmlNodeType.Element
&& DataReader.Name == "Name")
{
return DataReader.ReadContentAsString();
}
}
}
}
So for example, if 2
is passed to the function, I want it to return the string "Jane Doe"
. I'm new to XML parsing, so any help would be appreciated.
Thanks.
© Stack Overflow or respective owner