如何在 XPath 中使用变量? [英] How to use variables in XPath?

查看:41
本文介绍了如何在 XPath 中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Xpath 和 Java.

I am using Xpath and Java.

XML 有很多 OBJECT_TYPES 并且每个对象类型都有属性和参数.每个属性和参数都有元素.

The XML got plenty of OBJECT_TYPES and every object type has properties and parameters. And each property and parameter got elements.

如何从我的 XML 文件执行以下操作.我想知道如何使用 XPATH 字符串表达式选择所有属性元素,具体取决于 OBJECT_TYPE 字符串的名称.对象类型字符串名称取决于用户从列表中选择的名称.

How do I do the following from my XML file. I wanna know how to select with the XPATH string expression all property elements depending on whats the name of the OBJECT_TYPE string. The object type string name depends on what name the user selects from the list.

我该怎么做?

应该是这样的:

String expression = "/getObjType()/prop/*"; 

但是 getObjectType 是一种方法,所以我不能在字符串表达式中使用它.

But the getObjectType is a method so I cant use it in a string expression.

XML 看起来像这样:

XML looks something like this:

<type>
  <OBJECT_TYPE>SiteData</OBJECT_TYPE> 
  <prop>
    <DESCRIPTION>Site parameters</DESCRIPTION> 
    <PARENT>NULL</PARENT> 
    <VIRTUAL>0</VIRTUAL> 
    <VISIBLE>1</VISIBLE> 
    <PICTURE>NULL</PICTURE> 
    <HELP>10008</HELP> 
    <MIN_NO>1</MIN_NO> 
    <MAX_NO>1</MAX_NO> 
    <NAME_FORMAT>NULL</NAME_FORMAT> 
  </prop>
  <param>
    <PARAMETER>blabla</PARAMETER> 
    <DATA_TYPE>INTEGER</DATA_TYPE> 
    <DESCRIPTION>blaba</DESCRIPTION> 
    <MIN_NO>1</MIN_NO> 
    <MAX_NO>1</MAX_NO> 
    <ORDER1>1</ORDER1> 
    <NESTED>0</NESTED> 
    <DEFAULT1>NULL</DEFAULT1> 
    <FORMAT>0:16382</FORMAT> 
  </param>
  <OBJECT_TYPE>Data</OBJECT_TYPE> 
  <prop>
    <DESCRIPTION>Site parameters</DESCRIPTION> 
    <PARENT>NULL</PARENT> 
    <VIRTUAL>0</VIRTUAL> 
    <VISIBLE>1</VISIBLE> 
    <PICTURE>NULL</PICTURE> 
    <HELP>10008</HELP> 
    <MIN_NO>1</MIN_NO> 
    <MAX_NO>1</MAX_NO> 
    <NAME_FORMAT>NULL</NAME_FORMAT> 
  </prop>
  <param>
    <PARAMETER>gmgm</PARAMETER> 
    <DATA_TYPE>INTEGER</DATA_TYPE> 
    <DESCRIPTION>babla</DESCRIPTION> 
    <MIN_NO>1</MIN_NO> 
    <MAX_NO>1</MAX_NO> 
    <ORDER1>1</ORDER1> 
    <NESTED>0</NESTED> 
    <DEFAULT1>NULL</DEFAULT1> 
    <FORMAT>0:16382</FORMAT> 
  </param>
</type>

因此,根据 Object_type 的名称,我想要获取这些属性,并且我列出了 122 种对象类型,因此我必须使用变量来选择用户选择的类型.

So depending on whats the name of the Object_type I wanna get thoose properties and I have list 122 object types so I have to use a varible to pick which one the user selects.

 public class PropXMLParsing {

    static PropXMLParsing instance = null;

    private List<String> list = new ArrayList<String>();
    ObjType obj = new ObjType();

    public static PropXMLParsing getInstance() {

        if (instance == null) {

            instance = new PropXMLParsing();
            try {
                instance.ParserForObjectTypes();
            } catch (SAXException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            } catch (ParserConfigurationException e) {

                e.printStackTrace();
            }

        }

        return instance;

    }

    public void ParserForObjectTypes() throws SAXException, IOException,
            ParserConfigurationException {

        try {
            FileInputStream file = new FileInputStream(new File(
                    "xmlFiles/CoreDatamodel.xml"));

            DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                    .newInstance();

            builderFactory.setNamespaceAware(true);
            DocumentBuilder builder = builderFactory.newDocumentBuilder();

            Document xmlDocument = builder.parse(file);

            XPath xp = XPathFactory.newInstance().newXPath();
            final Map<String, Object> vars = new HashMap<String, Object>();
            xp.setXPathVariableResolver(new XPathVariableResolver() {
                public Object resolveVariable(QName name) {
                    return vars.get(name.getLocalPart());
                }
            });

            XPathExpression expr = xp
                    .compile("/type/OBJECT_TYPE[. = $type]/following-sibling::prop[1]");

            vars.put("type", obj.getObjectType());
            NodeList objectProps = (NodeList) expr.evaluate(xmlDocument,
                    XPathConstants.NODESET);
            System.out.println(objectProps);

            for (int i = 0; i < objectProps.getLength(); i++) {

                System.out.println(objectProps.item(i).getFirstChild()
                        .getNodeValue());
                list.add(objectProps.item(i).getFirstChild().getNodeValue());

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }

    public String convertListToString() {

        StringBuilder sb = new StringBuilder();
        if (list.size() > 0) {
            sb.append(list.get(0));
            for (int i = 1; i < list.size(); i++) {
                sb.append(list.get(i));
            }
        }
        return sb.toString();
    }

}

第二个解决方案我试过,它既不工作也不在控制台中打印出任何东西.

Second solution I have tried that aint working neither not printing out anything in the console.

public void ParserForObjectTypes() throws SAXException, IOException,
            ParserConfigurationException {

        try {
            FileInputStream file = new FileInputStream(new File(
                    "xmlFiles/CoreDatamodel.xml"));

            DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                    .newInstance();

            DocumentBuilder builder = builderFactory.newDocumentBuilder();

            Document xmlDocument = builder.parse(file);

            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodeList = (NodeList) xPath.compile(
                    "//OBJECT_TYPE[text() = '" + obj.getObjectType()
                            + "']/following-sibling::prop[1]/*").evaluate(
                    xmlDocument, XPathConstants.NODESET);

            for (int i = 0; i < nodeList.getLength(); i++) {
                System.out.println(nodeList.item(i).getNodeName() + " = "
                        + nodeList.item(i).getTextContent());
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }

推荐答案

此 XPATH 将选择 prop 元素中的所有元素,该元素位于 OBJECT_TYPE 之后,文本为 <代码>站点数据:

This XPATH will select all the elements within the prop element that follows the OBJECT_TYPE with the text SiteData:

//OBJECT_TYPE[text() = 'SiteData']/following-sibling::prop[1]/*

要更改选择的 OBJECT_TYPE,只需在代码中构建 XPATH:

To change the OBJECT_TYPE being selected just construct the XPATH in the code:

String xpath = "//OBJECT_TYPE[text() = '" + getObjType() + "']/following-sibling::prop[1]/*"

结果是这样的代码:

XPath xPath =  XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList)xPath.compile("//OBJECT_TYPE[text() = '" + getObjType() + "']/following-sibling::prop[1]/*").evaluate(document, XPathConstants.NODESET);

for (int i = 0; i < nodeList.getLength(); i++)
{
  System.out.println(nodeList.item(i).getNodeName() + " = " + nodeList.item(i).getTextContent());
}

给出问题中的 XML,当 getObjType() 返回 SiteData 打印:

That given the XML from the question and when getObjType() returns SiteData prints:

DESCRIPTION = Site parameters
PARENT = NULL
VIRTUAL = 0
VISIBLE = 1
PICTURE = NULL
HELP = 10008
MIN_NO = 1
MAX_NO = 1
NAME_FORMAT = NULL

这篇关于如何在 XPath 中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆