Xquery to get the value of a specific element from an XML which is stored as [XML Nullable column] in DB2

StackOverflow https://stackoverflow.com/questions/21087022

  •  27-09-2022
  •  | 
  •  

Consider the following XML :

     <Employee>
        <EmpDetails>   
             <Name>huff</Name>
        </EmpDetails>
     </Employee>

Above XMLis stored as a column(DATA) with data type [XML NULLABLE] in a table in DB2. Assume that the structure of the table is something like this:

      Table name:  REGEVENT
     Columns are: REFID (VARCHAR), APPID(VARCHAR), DATA(XML NULLABLE)

Suppose the value in the table is: REFID(12345), APPID(54321), DATA(Employee xml as mentioned above).

Now I have to get the value of element in the XML stored in column DATA using Xquery (Or any other way is also fine).

I am trying the following query, but I am getting the value EmpName as NULL.

select XMLCAST(XMLQUERY('$d/Employee/EmpDetails/Name' PASSING rg.DATA AS "d") AS VARCHAR(50)) AS EmpName from REGEVENT  rg where REFID='12345';
有帮助吗?

解决方案

I could not get the value using the XQUERY but instead first, I got the value of column 'DATA' as String and then used the following method (which uses Xpath) to get the value of the node 'Name'.

public String getEmpNameFromEmployee(String employeeXml)

  throws SAXException, IOException, XPathExpressionException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory
            .newInstance();
    DocumentBuilder builder = null;
    try {
        builder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    Document xmlDocument = builder.parse(new ByteArrayInputStream(employeeXml
            .getBytes()));
    XPath xPath = (XPath) XPathFactory.newInstance().newXPath();
    String expression = "/Employee/EmpDetails/Name";
    String empName = xPath.compile(expression).evaluate(
            xmlDocument);
    return empName;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top