Concatenating conditional XPaths - can this be done easier than this ugly expression?

ikantspelwurdz

Well-known member
Joined
Dec 8, 2009
Messages
49
Programming Experience
1-3
Take this XML:

VB.NET:
<Root>
  <SourceData>
    <Name>
      <Abbreviation>IRS</Abbreviation>
    </Name>
    <Type>
      <Code>T26</Code>
    </Type>
  </SourceData>
  <Employee>
    <FirstName>
      <FirstNames>
        <Name>Bill</Name>
      </FirstNames>
    </FirstName>
    <LastName>
      <LastNames>
        <Name>Gates</Name>
      </LastNames>
    </LastName>
  </Employee>
</Root>

I want an xpath expression to concatenate the FirstName and LastName, but only if the source is MS, or if the source type is T26. Otherwise, return null.

This is what I got right now:
VB.NET:
concat(/Root[SourceData/Name/Abbreviation='MS']/Employee/FirstName/FirstNames/Name|/Root[SourceData/Type/Code='T26']/Employee/FirstName/FirstNames/Name, ' ' , /Root[SourceData/Name/Abbreviation='MS']/Employee/LastName/LastNames/Name|/Root[SourceData/Type/Code='T26']/Employee/LastName/LastNames/Name)

It works, but it's long, unwieldy, and it will be very unpleasant to add new conditions.

Can this be improved on?

And this is my program:
VB.NET:
        Dim xml As String = GetXML()
        Dim address As String = "concat(/Root[SourceData/Name/Abbreviation='MS']/Employee/FirstName/FirstNames/Name|/Root[SourceData/Type/Code='T26']/Employee/FirstName/FirstNames/Name, ' ' , /Root[SourceData/Name/Abbreviation='MS']/Employee/LastName/LastNames/Name|/Root[SourceData/Type/Code='T26']/Employee/LastName/LastNames/Name)"
        Dim doc As XDocument = XDocument.Parse(xml)
        Dim x As String = doc.XPathEvaluate(address)
        Console.WriteLine(x)
        Console.ReadLine()

Only line #2 can be changed.
 

Similar threads

Back
Top