繁体   English   中英

JAVA DOM XML解析

[英]JAVA DOM XML Parse

我有一个要解析的大型XML文件

XML-XML文件有300多个案例和其他标签,我仅对案例感兴趣。 我想要做的是将所有案例和所有案例标签中的内容保存在一个仅包含案例的新DOM文档中,一旦有了这个新DOM,我想将其发送到另一个将采用信息和格式的类它变成一个word文档(但是一旦到达那儿,我就会说出来)

我的XML的示例是

   <suite>
<cases>
    <case>
        <id/>
        <title/>
        <type/>
        <priority/>
        <estimate/>
        <references/> 
        <custom>
            <functional_area/>
            <technology_dependence/>
            <reviewed/>
            <steps_completed>
            </steps_completed>
            <preconds> </preconds>
            <steps_seperated>
                <step>
                    <index/>
                    <content>
                    </content>
                    <expected>
                    </expected>
                </step>
                <step>
                    <index/>
                    <content>
                    </content>
                    <expected>
                    </expected>
                </step>
                <step>
                </steps_seperated>
            </custom>
        </case>
    </suite>
</cases>

这些案例节点大约有400个

我的java

设置初始

  private void setXMLdoc(String path){
     xmlDoc = getDocument(path) ;

}

获取xml文件

private Document getDocument(String path) {
    try{
        DocumentBuilderFactory  factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

         return builder.parse(path);

    } catch (ParserConfigurationException ex) {
        Logger.getLogger(ImportXML.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SAXException ex) {
        Logger.getLogger(ImportXML.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ImportXML.class.getName()).log(Level.SEVERE, null, ex);
    }  

   return null; 

  }    

这样会创建一个仅包含案例的新文档吗?

NodeList fList = xmlDoc.getElementsByTagName("case");

我还将如何打印出与案件相关的所有元素? /打印出所有情况下的所有元素

在此先感谢您-我仍然很新,如果这个问题没有道理或似乎有点基本,请抱歉

大概的代码是

DOMParser parser=new DOMParser();
InputSource source=new InputSource(<the XML file/network stream>);
parser.parse(source);
Element docElement=parser.getDocument().getDocumentElement();
XPath xPath=xPathFactory.newXPath();
XPathExpression expression_=xPath.compile("//case");
NodeList list_=(NodeList)expression_.evaluate(docElement,XPathConstants.NODESET);DocumentBuilder documentBuilder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document newDocument=documentBuilder.newDocument();
    Element newElement=newDocument.createElement("SOME_NAME");
    newDocument.appendChild(newElement);
    for(int i=0;i<list_.getLength();i++){Node n=newDocument.importNode(list_.item(i),true);newElement.appendChild(n);}

然后将“ newDocument”发送到另一个类

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM