Search code examples
xmlxpathxqueryxmlnodexml-attribute

How to use Xpath and Xquery to extract text() from an attribute?


Trying to query e-mail addresses using xpath and xquery but am not getting any results when

simple query:

xquery version "3.1";

for $contact in db:open("sample")

return $contact

data:

<Objs xmlns="http://schemas.microsoft.com/powershell/2004/04" Version="1.1.0.1">
  <Obj RefId="0">
    <TN RefId="0">
      <T>System.Management.Automation.PSCustomObject</T>
      <T>System.Object</T>
    </TN>
    <MS>
      <S N="First Name">a</S>
      <S N="Last Name">b</S>
      <S N="Emails">a@b;b@a.com</S>
      <S N="Phones">123 456-8904</S>
      <S N="Company Name"/>
    </MS>
  </Obj>
  <Obj RefId="1">
    <TNRef RefId="0"/>
    <MS>
      <S N="First Name">c</S>
      <S N="Last Name">c</S>
      <S N="Emails">e@f.com</S>
      <S N="Phones">123456-3532;563 346-3453</S>
      <S N="Company Name"/>
    </MS>
  </Obj>
</Objs>

I'm looking to get Objs/Obj/MS/S[N="emails"]/text() along those lines, for the actual content of the attribute.


Solution

  • I don't have your XML database...

    You can try something along the following.

    XQuery

    xquery version "3.1";
    
    declare namespace ns1="http://schemas.microsoft.com/powershell/2004/04" Version="1.1.0.1";
    
    for $contact in db:open("sample")//ns1:S[@N="Emails"]/text()
    return $contact