2

我有这个 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

4 回答 4

3

该类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());
}
于 2012-10-09T09:39:14.887 回答
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);
        }
    }
}
于 2012-10-09T09:43:55.637 回答
0

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

于 2012-10-09T09:55:21.757 回答
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();
    }
}
于 2014-08-12T10:17:25.723 回答