How do I access innerText of a specific XMLnode
Question
Hi I have the following XML fragment:
<Customer AccountNumber="4">
<CustomerInfo>
<firstName>Andrew</firstName>
<lastName>Walker</lastName>
</CustomerInfo>
<Transactions>
<AccountBalance>595848584.4</AccountBalance>
</Transactions>
</Customer>
from a bigger XML file. I want to access the <firsName>
in C#.
Currently I am doing the following:
foreach (XmlNode customer in root)
{
i++;
if(_AccNumber== Convert.ToInt32(customer.Attributes[0].Value))
{
searchNode = CustNodes[(i - 1)];
string _firstName = searchNode.FirstChild.FirstChild.InnerText;
}
}
When I view searchNode
in the debugger I can see in the results view element [0] which has a localName
CustomerInfo
as you expect. So in the debugger first name has the following path:
searchNode -> [0].[0].[0].value
if that makes sense?
Is there any better way of doing this? (without LINQ)? Apologies, if something isn't clear....its 2:30AM! Let me know and I'll explain myself better. Thanks!!
Solution
I think xpath is so much complex to understand , so better to use the GetElementsByTagName function
XmlDocument doc = new XmlDocument();
doc.Load(@"sample.xml");
XmlNodeList firstNameNodes = doc.GetElementsByTagName("firstName");
foreach (XmlNode node in firstNameNodes)
{
string firstName = node.InnerText;
}
OTHER TIPS
Try XPath.. something like this should work:
string firstName = String.Empty;
var xmlNode = doc.SelectSingleNode(String.Format("//Customer[@AccountNumber='{0}']/CustomerInfo/firstName", _AccNumber));
if (xmlNode != null)
firstName = xmlNode.InnerText;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow