使用xpath获取xsi:type的值

J. *_*ugh 6 xml xpath xsd eai spring-integration

我试图确定正确的XPath表达式,以返回元素的xsi:type属性值Body.我没有运气就尝试了所有的东西.根据我读到的内容,这似乎很接近,但显然不是正确的.任何快速指导,以便我终于可以休息了吗?

//v20:Body/@xsi:type
Run Code Online (Sandbox Code Playgroud)

我想要它回来 v20:SmsMessageV1RequestBody

<v20:MessageV1Request>
    <v20:Header>
        <v20:Source>
            <v20:Name>SOURCE_APP</v20:Name>
            <v20:ReferenceId>1326236916621</v20:ReferenceId>
            <v20:Principal>2001</v20:Principal>
        </v20:Source>
    </v20:Header>
    <v20:Body xsi:type="v20:SmsMessageV1RequestBody">
        <v20:ToAddress>5555551212</v20:ToAddress>
        <v20:FromAddress>11111</v20:FromAddress>
        <v20:Message>TEST</v20:Message>
    </v20:Body>
</v20:MessageV1Request>
Run Code Online (Sandbox Code Playgroud)

Way*_*ett 2

正如评论中指出的,您有两种选择:

  1. 用于local-name()引用目标节点而不考虑命名空间
  2. 使用 XPath 引擎正确注册所有名称空间

以下是在 Java 中执行后者的方法:

XPath xpath = XPathFactory.newInstance().newXPath();
NamespaceContext ctx = new NamespaceContext() {
    public String getNamespaceURI(String prefix) {
        if ("v20".equals(prefix)) {
            return "testNS1";
        } else if ("xsi".equals(prefix)) {
            return "http://www.w3.org/2001/XMLSchema-instance";
        }
        return null;
    }
    public String getPrefix(String uri) {
        throw new UnsupportedOperationException();
    }
    public Iterator getPrefixes(String uri) {
        throw new UnsupportedOperationException();
    }
};
xpath.setNamespaceContext(ctx);
XPathExpression expr = xpath.compile("//v20:Body/@xsi:type");       
System.out.println(expr.evaluate(doc, XPathConstants.STRING));
Run Code Online (Sandbox Code Playgroud)

请注意,我假设以下命名空间声明:

<v20:MessageV1Request xmlns:v20="testNS1" 
                      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
Run Code Online (Sandbox Code Playgroud)

您需要更新getNamespaceURI才能使用实际值。