XML/C#: Read content if only if attribute is correct
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.
Use XPath for this.
Check this article: http://www.developer.com/xml/article.php/3383961/NET-and-XML-XPath-Queries.htm. It has an example that is very similar to your situation.
Could you try something like this:-
public static string GetName(int EmployeeNumber)
{
XmlDocument doc = new XmlDocument();
doc.Load("Database.xml");
XmlElement rootNode = doc.DocumentElement;
String query ="Record[@Number='"+EmployeeNumber.ToString()+"']/Name";
XmlNode data= rootNode.SelectSingleNode(query);
return data.InnerText;
}
You could use XPath if your XML is not very large:
using System;
using System.Xml.Linq;
using System.Xml.XPath;
public class Program
{
static void Main(string[] args)
{
var elements = XDocument.Load("Database.xml")
.XPathSelectElements("//Record[@Number='2']/Name");
foreach (var item in elements)
{
Console.WriteLine(item.Value);
}
}
}
string searchTerm = "2";
var list = from XElement segment in workingXmlDocument.Descendants(wix + "File")
where segment.Attribute("Id").Value.ToString() == searchTerm
select segment.Descendant("Name").Value;
That is a LINQ statement that will give you the name based on the variable searchTerm.
精彩评论