CompanyDroneFromSector7G
CompanyDroneFromSector7G

Reputation: 4517

XPath to select nodes whose name starts with

I have XML that looks like this:

<detail>
  <address>
    <line1/>
    <line2/>
    <line3/>
    <postcode/>
  </address>
</detail/>

There could be any number of <line*> nodes which I want to select, and other nodes which I don't want to select.

I have tried this, which doesn't seem to work (in C# anyway):

/detail/address/[substring(name(),4) = 'line']

Al, help appreciated!

Upvotes: 2

Views: 7054

Answers (4)

albciff
albciff

Reputation: 18507

You can try with contains:

/detail/address/*[contains(name(),'line')]

If you want to use substring you've to know that the index starts with 1 and you're also missing the wildcard:

/detail/address/*[substring(name(),1,4) = 'line']

Upvotes: 2

Stephen Walker
Stephen Walker

Reputation: 574

Consider using XDocuments.

        XDocument doc = XDocument.Parse(xmlString);
        foreach (XElement element in doc.Descendants())
        {

            if(element.Name.LocalName.StartsWith("line"))
               //DoStuffWithValueOfThatElement(element.Value)...
        }

Upvotes: 2

AGB
AGB

Reputation: 2448

From memory, I think the index is 1 based not 0 based. Perhaps this will work:

/detail/address/[substring(name(),1,3) = 'line']

Alternatively, do you have control over the format of the XML? If so, a better approach might be to structure it like so:

<detail>
  <address>
    <line number='1'/>
    <line number='2'/>
    <line number='3'/>
    <postcode/>
  </address>
</detail/>

Then you can use the following to retrieve the lines:

/detail/address/line

Upvotes: 1

Joel M. Lamsen
Joel M. Lamsen

Reputation: 7173

try

/detail/address/*[starts-with(name(), 'line')]

Upvotes: 7

Related Questions