使用Java中的xpath查询表达式获取XML中Root元素的属性

时间:2012-10-09 09:32:57

标签: java xml xpath

我有这个XML

     <Results SchemaVersion="1.0" SchemaType="Results" GroupId="-12345" 
     xmlns="http://xyz"  xmlns:xs="http://www.w3.org/2001/XMLSchema-instance">
            <Attempt>
                            <Time>2007-03-30T15:58:15</Time>
                            <Message>This is some message</Message>
            </Attempt>
            <Attempt>
                            <Time>2007-03-30T15:59:45</Time>
                            <Message>This is some other message</Message>
            </Attempt>
      </Results>

我在Java中使用这个代码来解析上面的xml。我想使用xpath查询获取xml中的根元素的属性。我能够检索根元素的值,但不能检索属性。 注意:在这种情况下我不知道属性名称,否则我可以直接访问这些属性

    public class Try {

      public static void main(String args[]){

       try{
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true); 
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse("C:/Documents and Settings/tulans/workspace/WebServiceTool/src/main/resources/Input.xml");
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xpath.compile("/*");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;     
        System.out.println(nodes.item(0).getLocalName());
        System.out.println(nodes.item(0).getNodeName());

       }catch(Exception e){
         System.out.println(e);
       }
     }
    }

我得到以下结果:

    Results
    Results

我也想要根元素属性:

     SchemaVersion="1.0" SchemaType="Results" GroupId="-12345" 
     xmlns="http://xyz"  xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"

4 个答案:

答案 0 :(得分:2)

Node类有一个getAttributes方法可以满足您的需求:

NamedNodeMap attributes = nodes.item(0).getAttributes();
for (int i=0, len=attributes.getLenght(); i<len; i++) {
   Attr attr = (Attr)attributes.item(i);
   System.out.println(attr.getName() + "=" + attr.getValue());
}

答案 1 :(得分:1)

public class Try {

    public static void main(String args[]){

        try{
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document doc = builder.parse("Input.xml");
            XPath xpath = XPathFactory.newInstance().newXPath();
            XPathExpression expr = xpath.compile("/*");
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            System.out.println(nodes.item(0).getLocalName());
            System.out.println(nodes.item(0).getNodeName());
            NamedNodeMap attributes = nodes.item(0).getAttributes();
            for (int i = 0; i < attributes.getLength(); i++) {
                System.out.println(attributes.item(i));
            }

        }catch(Exception e){
            System.out.println(e);
        }
    }
}

答案 2 :(得分:0)

Don和Jörn已经向您展示了如何访问DOM树中的属性节点;因为您已经要求使用XPath来访问它们,我将展示一个替代方案,您可以简单地使用XPath表达式/*/@*来访问XPath数据模型中根元素的属性节点。但请注意,命名空间声明不是XPath数据模型中的属性节点,因此路径只能找到属性SchemaVersion="1.0" SchemaType="Results" GroupId="-12345"。因此,根据您想要的结果,您最好使用DOM getAttributes而不是XPath。

答案 3 :(得分:0)

public static void executeXMLToCSV() {
    File fXmlFile = new File(fileLocation);
    List<String> recordIndexCSVList = new ArrayList<String>();
    String recordIndexCSV = "";

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = null;
        try {
            doc = dBuilder.parse(fXmlFile);
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        doc.getDocumentElement().normalize();
        NodeList rootsite = doc.getElementsByTagName("sites");
        Node rootsiteNode = rootsite.item(0);
        NodeList sites = rootsiteNode.getChildNodes();
        for (int siteCtr = 0; siteCtr < sites.getLength(); siteCtr++) {
            Node siteNode = sites.item(siteCtr);
            System.out.println("\nCurrent Element :"
                    + siteNode.getNodeName());
            if (siteNode.getNodeType() == Node.ELEMENT_NODE
                    && "site".equalsIgnoreCase(siteNode.getNodeName())) {
                Element eElement = (Element) siteNode;
                String siteId = eElement.getAttribute("id");
                String siteName = eElement.getAttribute("name");
                System.out.println("Staff id : " + siteId);
                System.out.println("Staff name : " + siteName);

                NodeList categories = siteNode.getChildNodes();
                for (int categoryCtr = 0; categoryCtr < categories
                        .getLength(); categoryCtr++) {
                    Node categoryNode = categories.item(categoryCtr);
                    System.out.println("\nCurrent Element :"
                            + categoryNode.getNodeName());
                    Element cElement = (Element) categoryNode;
                    String categoryId = cElement.getAttribute("id");
                    String categoryName = cElement.getAttribute("name");
                    System.out.println("categoryId : " + categoryId);
                    System.out.println("categoryName : " + categoryName);

                    NodeList fleets = categoryNode.getChildNodes();
                    for (int fleetCtr = 0; fleetCtr < fleets.getLength(); fleetCtr++) {
                        Node fleetNode = fleets.item(fleetCtr);
                        System.out.println("\nCurrent Element :"
                                + fleetNode.getNodeName());
                        Element fElement = (Element) fleetNode;
                        String fleetId = fElement.getAttribute("id");
                        String fleetName = fElement.getAttribute("name");
                        System.out.println("fleetId : " + fleetId);
                        System.out.println("fleetName : " + fleetName);

                        NodeList fleetChilds = fleetNode.getChildNodes();
                        for (int fleetChildCtr = 0; fleetChildCtr < fleetChilds
                                .getLength(); fleetChildCtr++) {
                            Node fleetChild = fleetChilds
                                    .item(fleetChildCtr);
                            if ("assets".equalsIgnoreCase(fleetChild
                                    .getNodeName())) {
                                NodeList assets = fleetChild
                                        .getChildNodes();
                                for (int assetCtr = 0; assetCtr < assets
                                        .getLength(); assetCtr++) {
                                    Node asset = assets.item(assetCtr);
                                    Element aElement = (Element) asset;
                                    String assetId = aElement
                                            .getAttribute("id");
                                    System.out.println("assetId : "
                                            + assetId);
                                    /*
                                     * Finally prepare a list of csv
                                     * strings... after this loop iterate
                                     * the list and prepare the final string
                                     * by concanating all.
                                     */
                                    String recordIndexCSV_index = siteId
                                            + "_" + categoryId + "_"
                                            + fleetId + "_" + assetId;
                                    String recordIndexCSVString = recordIndexCSV_index
                                            + delimeter
                                            + siteId
                                            + delimeter
                                            + categoryId
                                            + delimeter
                                            + fleetId
                                            + delimeter + assetId;
                                    recordIndexCSVList
                                            .add(recordIndexCSVString);
                                }
                            }
                        }
                    }
                }
            }
        }

        for (String recordIndexCSVString : recordIndexCSVList) {
            if ("".equals(recordIndexCSV)) {
                recordIndexCSV = recordIndexCSV + recordIndexCSVString;
            } else {
                recordIndexCSV = recordIndexCSV + seperator
                        + recordIndexCSVString;
            }
        }
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}