问题描述:

From the following XML, I want to find a value based on the Employer.

<?xml version="1.0" encoding="UTF-8"?>

<Document>

<Details>

<Employer>Taxes</Employer>

<Adr>

<Strt>Street</Strt>

<Twn>Town</Twn>

</Adr>

</Details>

<DetailsAcct>

<Recd>

<Payroll>

<Id>9</Id>

</Payroll>

</Recd>

<br>

<xy>A</xy>

</br>

</DetailsAcct>

</Document>

the C# code I applied is

 detail = root.SelectSingleNode($"//w:Document//w:Employer[contains(text(), 'Taxes']/ancestor::Employer",nsmgr);

But it gives me an invalid token error.

What am I missing?

网友答案:

The error was due to [contains(...], notice closing parentheses is missing. And since you want to return Employer element, no need for ancestor::Employer here :

//w:Document//w:Employer[contains(., 'Taxes')]

If the XML posted resembles structure of the actual XML (except the namespaces), better to use more specific XPath i.e avoid using costly // :

/w:Document/w:Details/w:Employer[contains(., 'Taxes')]
网友答案:

An alternative is to use LINQ to XML.

If the XML is in a string:

string xml = "<xml goes here>";
XDocument document = XDocument.Parse(xml);
XElement element = document.Descendants("Employer").First();
string value = element.Value;

If the XML is in a .xml file:

XDocument document = XDocument.Load("xmlfile.xml");
XElement element = document.Descendants("Employer").First();
string value = element.Value;

You can also find an employer element with a specific value, if that's what you need:

XElement element = document.Descendants("Employer").First(e => e.Value == "Taxes");

Note: this will throw an exception if no element is found with the specified value. If that is not acceptable, then you can replace .First(...) with .FirstOrDefault(...) which will simply return null if no element is found.

相关阅读:
Top