在Java中针对String执行Xpath的简单方法?

时间:2016-09-13 01:09:57

标签: java xml xpath

我知道类似于这个问题的问题已被多次询问(和回答),我已经尝试过很多建议,但由于某种原因,我无法让这个工作得以实现。

我在String变量中有一个XML文档(在“compositeBodyLine”中),我想对该XML文档执行Xpath搜索并从该Xpath搜索中获取结果。

我该怎么做?

这是我尝试过的一个例子(或实际合并了我发现的几件不同的东西:

 // From: http://javarevisited.blogspot.com/2012/12/create-and-evaluate-xpath-java-example-tutorial-program.html

  //Create DocumentBuilderFactory for reading xml file
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();

  InputStream inputStream = new    ByteArrayInputStream(compositeBodyLine.getBytes());
  org.w3c.dom.Document doc = builder.parse(inputStream);

   System.out.println("doc.getParentNode()=[" + doc.getParentNode().toString() + "]");

  // Create XPathFactory for creating XPath Object
  XPathFactory xPathFactory = XPathFactory.newInstance();

  // Create XPath object from XPathFactory
  XPath xpath = xPathFactory.newXPath();

  // Compile the XPath expression for getting all brands
  XPathExpression xPathExpr = xpath.compile("/soapEnv:Envelope");

  // XPath text example : executing xpath expression in java
  Object result = xPathExpr.evaluate(doc, XPathConstants.NODESET);
  System.out.println("Java Xpath text example: All brands of popular smartphones ");

  printXpathResult(result);

.
.
.
.
public static org.w3c.dom.Document loadXMLFromString(String xml) throws Exception
{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(xml));
    return builder.parse(is);
}

当我尝试上面的代码时,我得到null返回。我认为我看过的大多数示例都将文件作为输入,而在我的情况下,我将XML文档放在String变量中,所以如果我不得不猜测,我会猜测我遇到了问题。 XML输入。

有人可以提供一种简单的方法来实现这一目标吗?

谢谢, 吉姆

编辑:以下是输入XML的示例:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soapenv:Body>
        <Request xmlns:xacml-context="urn:oasis:names:tc:xacml:2.0:context:schema:os" xmlns:ns9="urn:oasis:xacml:2.0:saml:assertion:schema:os" xmlns:ns8="urn:oasis:xacml:2.0:saml:protocol:schema:os" xmlns:ns7="http://security.bea.com/ssmws/ssm-soap-types-1.0.xsd" xmlns:ns6="http://www.w3.org/2001/04/xmlenc#" xmlns:ns5="urn:oasis:names:tc:xacml:2.0:policy:schema:os" xmlns:ns4="urn:oasis:names:tc:xacml:2.0:context:schema:os" xmlns:ns3="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" xmlns="urn:oasis:names:tc:xacml:2.0:context:schema:os">
            <Subject>
                <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" DataType="http://security.bea.com/ssmws/ssm-ws-1.0.wsdl#OESPrincipalInfo">

                    <AttributeValue>{name=jimXXXX1234}+(class=weblogic.security.principal.WLSUserImpl)</AttributeValue>
                </Attribute>
<!-- FOLLOWING IS **THE** GOOD WAY AND DOES WORK WITH OES FOR ROLE -->
<Attribute AttributeId="http://oracle.com/symbols/oes/attribute/group-assertion" DataType="http://security.bea.com/ssmws/ssm-ws-1.0.wsdl#OESPrincipalInfo" xsi:type="ns1:AttributeType"> 
<AttributeValue xsi:type="ns1:AttributeValueType">{name=Operators}+(class=weblogic.security.principal.WLSGroupImpl)</AttributeValue> 
</Attribute> 
            </Subject>
            <Resource>
                <Attribute AttributeId="urn:oasis:names:tc:xacml:2.0:resource:resource-id" DataType="http://www.w3.org/2001/XMLSchema#string">
                    <AttributeValue>foo/foo1/foo2</AttributeValue>
                </Attribute>
            </Resource>
            <Action>
                <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" DataType="http://www.w3.org/2001/XMLSchema#string">
                    <AttributeValue>GET</AttributeValue>
                </Attribute>
            </Action>
<ns4:Environment xsi:type="ns4:EnvironmentType" 
     xmlns:ns4="urn:oasis:names:tc:xacml:2.0:context:schema:os" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ns4:Attribute AttributeId="http://security.bea.com/ssmws/ssm-ws-1.0.wsdl#RegisteredAttribute" 
     DataType="http://www.w3.org/2001/XMLSchema#string" xsi:type="ns4:AttributeType">
    <ns4:AttributeValue xsi:type="ns4:AttributeValueType">4444444444yes</ns4:AttributeValue> 
  </ns4:Attribute>
  <ns4:Attribute AttributeId="http://security.bea.com/ssmws/ssm-ws-1.0.wsdl#NumberOfBorrowedBooksAttribute" 
       DataType="http://www.w3.org/2001/XMLSchema#string" xsi:type="ns4:AttributeType">
        <ns4:AttributeValue xsi:type="ns4:AttributeValueType">abc</ns4:AttributeValue> 
  </ns4:Attribute>
</ns4:Environment>
                  </Request>
    </soapenv:Body>
</soapenv:Envelope>

1 个答案:

答案 0 :(得分:1)

Steve,其原因可能是您在XML上拥有的命名空间。克服这种情况的一种方法是注册名称空间。一种更简单的方法可能是使用本地名称。程序的较短版本如下所示,它确实返回了一个按预期设置的节点。我在这里创建了一个最低测试程序,请告诉我这是否适用于您可能拥有的其他XPATH

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

public class XPathClass {
    public static void main(String[] args) throws Exception {
        String soapXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">    <soapenv:Body>        <Request xmlns:xacml-context=\"urn:oasis:names:tc:xacml:2.0:context:schema:os\" xmlns:ns9=\"urn:oasis:xacml:2.0:saml:assertion:schema:os\" xmlns:ns8=\"urn:oasis:xacml:2.0:saml:protocol:schema:os\" xmlns:ns7=\"http://security.bea.com/ssmws/ssm-soap-types-1.0.xsd\" xmlns:ns6=\"http://www.w3.org/2001/04/xmlenc#\" xmlns:ns5=\"urn:oasis:names:tc:xacml:2.0:policy:schema:os\" xmlns:ns4=\"urn:oasis:names:tc:xacml:2.0:context:schema:os\" xmlns:ns3=\"urn:oasis:names:tc:SAML:2.0:protocol\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns=\"urn:oasis:names:tc:xacml:2.0:context:schema:os\">            <Subject>                <Attribute AttributeId=\"urn:oasis:names:tc:xacml:1.0:subject:subject-id\" DataType=\"http://security.bea.com/ssmws/ssm-ws-1.0.wsdl#OESPrincipalInfo\">                    <AttributeValue>{name=jimlum1234}+(class=weblogic.security.principal.WLSUserImpl)</AttributeValue>                </Attribute><!-- FOLLOWING IS **THE** GOOD WAY AND DOES WORK WITH OES FOR ROLE --><Attribute AttributeId=\"http://oracle.com/symbols/oes/attribute/group-assertion\" DataType=\"http://security.bea.com/ssmws/ssm-ws-1.0.wsdl#OESPrincipalInfo\" xsi:type=\"ns1:AttributeType\"> <AttributeValue xsi:type=\"ns1:AttributeValueType\">{name=Operators}+(class=weblogic.security.principal.WLSGroupImpl)</AttributeValue> </Attribute>             </Subject>            <Resource>                <Attribute AttributeId=\"urn:oasis:names:tc:xacml:2.0:resource:resource-id\" DataType=\"http://www.w3.org/2001/XMLSchema#string\">                    <AttributeValue>foo/foo1/foo2</AttributeValue>                </Attribute>            </Resource>            <Action>                <Attribute AttributeId=\"urn:oasis:names:tc:xacml:1.0:action:action-id\" DataType=\"http://www.w3.org/2001/XMLSchema#string\">                    <AttributeValue>GET</AttributeValue>                </Attribute>            </Action><ns4:Environment xsi:type=\"ns4:EnvironmentType\"      xmlns:ns4=\"urn:oasis:names:tc:xacml:2.0:context:schema:os\"      xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">  <ns4:Attribute AttributeId=\"http://security.bea.com/ssmws/ssm-ws-1.0.wsdl#RegisteredAttribute\"      DataType=\"http://www.w3.org/2001/XMLSchema#string\" xsi:type=\"ns4:AttributeType\">    <ns4:AttributeValue xsi:type=\"ns4:AttributeValueType\">4444444444yes</ns4:AttributeValue>   </ns4:Attribute>  <ns4:Attribute AttributeId=\"http://security.bea.com/ssmws/ssm-ws-1.0.wsdl#NumberOfBorrowedBooksAttribute\"        DataType=\"http://www.w3.org/2001/XMLSchema#string\" xsi:type=\"ns4:AttributeType\">        <ns4:AttributeValue xsi:type=\"ns4:AttributeValueType\">abc</ns4:AttributeValue>   </ns4:Attribute></ns4:Environment>                  </Request>    </soapenv:Body></soapenv:Envelope>";
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(soapXML.getBytes()));

        XPathFactory xPathFactory = XPathFactory.newInstance();

        // Create XPath object from XPathFactory
        XPath xpath = xPathFactory.newXPath();

        // Compile the XPath expression for getting all brands
        XPathExpression xPathEnvelopeExpr = xpath.compile("//*[local-name()='Envelope']");
        Object result = xPathEnvelopeExpr.evaluate(doc, XPathConstants.NODESET);
        System.out.println("Java Xpath text example: All brands of popular smartphones " + result);

    }

}