Java XML 获取属性

发布于 2024-11-15 08:01:08 字数 2860 浏览 0 评论 0原文

我正在尝试从 XML 文档中获取属性 id (fileID),以用作 XML 拆分的文件名。拆分工作正常,我只需要提取 fileID 用作名称即可。

我可以用它来帮助解决这个问题。

这是我的 xml 文档

<root>
 <envelope fileID="000152OP.XML">
   <record id="850">
   </record>
</envelope>
<envelope fileID="000153OP.XML">
  <record id="850">
  </record>
</envelope>
<envelope fileID="000154OP.XML">
  <record id="850">
  </record>
</envelope>
</root>

这是我的 Java 代码 [已编辑] 我现在可以读取该属性,但它不会创建最后一个 xml 文件。因此,在我的示例中,它创建了具有正确名称的前 2 个文件,但未创建最后一个文件 ID“000154OP.XML”。

    public static void splitXMLFile (String file) throws Exception {         
    String[] temp;
    String[] temp2;
    String[] temp3;
    String[] temp4;
    String[] temp5;
    String[] temp6;
    File input = new File(file);         
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();         
    Document doc = dbf.newDocumentBuilder().parse(input);
    XPath xpath = XPathFactory.newInstance().newXPath();          
    NodeList nodes = (NodeList) xpath.evaluate("//root/envelope", doc, XPathConstants.NODESET);          
    int itemsPerFile = 1;         

    Node staff = doc.getElementsByTagName("envelope").item(0);

    NamedNodeMap attr = staff.getAttributes();
    Node nodeAttr = attr.getNamedItem("fileID");
    String node = nodeAttr.toString();
    temp = node.split("=");
    temp2 = temp[1].split("^\"");
    temp3 = temp2[1].split("\\.");

    Document currentDoc = dbf.newDocumentBuilder().newDocument();         
    Node rootNode = currentDoc.createElement("root");   
    File currentFile = new File("C:\\XMLFiles\\" + temp3[0]+ ".xml"); 

    for (int i=1; i <= nodes.getLength(); i++) {             
        Node imported = currentDoc.importNode(nodes.item(i-1), true);             
        rootNode.appendChild(imported); 

        Node staff2 = doc.getElementsByTagName("envelope").item(i);
        NamedNodeMap attr2 = staff2.getAttributes();
        Node nodeAttr2 = attr2.getNamedItem("fileID");
        String node2 = nodeAttr2.toString();
        temp4 = node2.split("=");
        temp5 = temp4[1].split("^\"");
        temp6 = temp5[1].split("\\.");

        if (i % itemsPerFile == 0) { 

            writeToFile(rootNode, currentFile);                  
            rootNode = currentDoc.createElement("root");    
            currentFile = new File("C:\\XMLFiles\\" + temp6[0]+".xml");


        }         
    }          
    writeToFile(rootNode, currentFile);     
}    

 private static void writeToFile(Node node, File file) throws Exception {         
     Transformer transformer = TransformerFactory.newInstance().newTransformer();         
     transformer.transform(new DOMSource(node), new StreamResult(new FileWriter(file)));     
 } 

I'm trying to get an attribute id (fileID) from my XML document to use as the filename for my XML split. The split works I just need to extract the fileID to use as the name.

I could use this as help on this.

This is my xml document

<root>
 <envelope fileID="000152OP.XML">
   <record id="850">
   </record>
</envelope>
<envelope fileID="000153OP.XML">
  <record id="850">
  </record>
</envelope>
<envelope fileID="000154OP.XML">
  <record id="850">
  </record>
</envelope>
</root>

And here's my Java code [EDITED] I can read the attribute now but it doesn't create the last xml file. So in my example it create the first 2 files with the correct name but last fileID "000154OP.XML" isn't created.

    public static void splitXMLFile (String file) throws Exception {         
    String[] temp;
    String[] temp2;
    String[] temp3;
    String[] temp4;
    String[] temp5;
    String[] temp6;
    File input = new File(file);         
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();         
    Document doc = dbf.newDocumentBuilder().parse(input);
    XPath xpath = XPathFactory.newInstance().newXPath();          
    NodeList nodes = (NodeList) xpath.evaluate("//root/envelope", doc, XPathConstants.NODESET);          
    int itemsPerFile = 1;         

    Node staff = doc.getElementsByTagName("envelope").item(0);

    NamedNodeMap attr = staff.getAttributes();
    Node nodeAttr = attr.getNamedItem("fileID");
    String node = nodeAttr.toString();
    temp = node.split("=");
    temp2 = temp[1].split("^\"");
    temp3 = temp2[1].split("\\.");

    Document currentDoc = dbf.newDocumentBuilder().newDocument();         
    Node rootNode = currentDoc.createElement("root");   
    File currentFile = new File("C:\\XMLFiles\\" + temp3[0]+ ".xml"); 

    for (int i=1; i <= nodes.getLength(); i++) {             
        Node imported = currentDoc.importNode(nodes.item(i-1), true);             
        rootNode.appendChild(imported); 

        Node staff2 = doc.getElementsByTagName("envelope").item(i);
        NamedNodeMap attr2 = staff2.getAttributes();
        Node nodeAttr2 = attr2.getNamedItem("fileID");
        String node2 = nodeAttr2.toString();
        temp4 = node2.split("=");
        temp5 = temp4[1].split("^\"");
        temp6 = temp5[1].split("\\.");

        if (i % itemsPerFile == 0) { 

            writeToFile(rootNode, currentFile);                  
            rootNode = currentDoc.createElement("root");    
            currentFile = new File("C:\\XMLFiles\\" + temp6[0]+".xml");


        }         
    }          
    writeToFile(rootNode, currentFile);     
}    

 private static void writeToFile(Node node, File file) throws Exception {         
     Transformer transformer = TransformerFactory.newInstance().newTransformer();         
     transformer.transform(new DOMSource(node), new StreamResult(new FileWriter(file)));     
 } 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无声静候 2024-11-22 08:01:08

也许您可以尝试以下 xpath:

//root/envelope/record/@id

如果您使用的 XPath 库不支持整个 XPath 集,您可以尝试优秀的库 jaxen

Perhaps you can try the following xpath:

//root/envelope/record/@id

If the XPath library you're using does not support the entire XPath set you can try the excellent library jaxen

桃气十足 2024-11-22 08:01:08
ArrayList<String> files = new ArrayList<String>();   
SAXBuilder builder = new SAXBuilder();
Document Doc;
    try {
        Doc = builder.build(new File(myxmlfile.xml));
        Element root = Doc.getRootElement();
        List<Element> category = root.getChildren();
        for(int i=0 ; i < category.size(); i++) {
            Element elem = category.get(i);
            String file = elem.getAttributeValue("fileID");
                            files.add(file);
        }

    } catch (Exception e) {

    }

这将为您提供 XML 文件中 fileId 的数组列表。我使用 SAX 阅读器来解析 XML。

ArrayList<String> files = new ArrayList<String>();   
SAXBuilder builder = new SAXBuilder();
Document Doc;
    try {
        Doc = builder.build(new File(myxmlfile.xml));
        Element root = Doc.getRootElement();
        List<Element> category = root.getChildren();
        for(int i=0 ; i < category.size(); i++) {
            Element elem = category.get(i);
            String file = elem.getAttributeValue("fileID");
                            files.add(file);
        }

    } catch (Exception e) {

    }

This will give you an array list of the fileIds in the XML file. I've used the SAX reader to parse the XML.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文