简体   繁体   English

Java:读取具有许多嵌套元素的xml

[英]Java: reading xml with many nested elements

I have xml that looks somewhat similar to the following. 我有看起来与以下内容类似的xml。 I need to get values from attributes and tags and store them. 我需要从属性和标签中获取值并存储它们。 But i cant understand how to get to level 2(3,4, etc) nested elements. 但是我不明白如何到达2(3,4等)嵌套元素。 I use following code that i found on the internet, it uses DOM but i cant get correct RegNumber and its attributes. 我使用以下代码在Internet上找到,它使用DOM,但是我无法获取正确的RegNumber及其属性。 Thanks in advance. 提前致谢。

 nodeList = xmldocument.getElementsByTagName("Header"); if (nodeList != null && nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { //get the header element Element header = (Element) nodeList.item(i); System.out.println("Element: " + ((Element)nodeList.item(i)).getNodeName()); System.out.println(header.getAttribute("time")); } } nodeList = xmldocument.getElementsByTagName("Document"); if (nodeList != null && nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { //get the document element Element document = (Element) nodeList.item(i); System.out.println("Element: " + ((Element)nodeList.item(i)).getNodeName()); System.out.println(document.getAttribute("Id")); nodeList = document.getElementsByTagName("RegNumber"); for (int j = 0; j < nodeList.getLength(); j++) { //get the RegNumber element Element regNumber = (Element) nodeList.item(j); System.out.println("Element: " + ((Element)nodeList.item(j)).getNodeName()); System.out.println(regNumber.getAttribute("regpoint")); } } } 

xml: xml:

<XML xsi:schemaLocation="http://www.codetools.it XSD2.xsd" xmlns="http://www.codetools.it" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <Header time="2001-12-17T09:30:47Z" />
            <Document Id="456">
                <RegNumber regpoint="" regdate="2001-12-17T09:30:47Z">123/456</RegNumber>
                <Confident flag="0"/>
                <DocNumber kind="">
                    <RegNumber RegPoint="" regdate="2001-12-17T09:30:47Z">456/789</RegNumber>
                    <Organization fullname="lol" shortname="" ownership="lol" ogrn="78945612" inn="">
                        <OfficialPerson>
                            <Name  Firstname="John"/>
                            <Official Department="" post=""/>
                            <SignDate>2001-12-17T09:30:47Z</SignDate>
                        </OfficialPerson>
                        <Econtact type="1">test@test.com.ua</Econtact>
                        <Address street="" settlement="" postcode="" postbox="" flat="" district="" region="" country="" nontypical="" house=""/>
                    </Organization>
                </DocNumber>
                <DocTransfer os="Windows" type=".docx" type_ver="" char_set="" description="kkkk">
    </DocTransfer>
            <Reghistory idnumber="">
                <RegNumber RegPoint="" regdate=""/>
                <Organization fullname="" shortname="" ownership="" ogrn="" inn="">
                    <Econtact type=""/>
                    <Address street="" settlement="" postcode="" postbox="" flat="" district="" region="" country="" nontypical="" house=""/>
                </Organization>
            </Reghistory>
            <Author>
                <Organization fullname="" shortname="" ownership="" ogrn="12345678" inn="">
                    <OfficialPerson>
                        <Name  Firstname="" />
                        <Official Department="" post=""/>
                        <SignDate>2011-12-17T09:30:47Z</SignDate>
                    </OfficialPerson>
                    <Econtact type="Рї">smirnov@test.com</Econtact>
                    <Address street=""  postcode="1234" postbox="" flat="" district="" region="" country="" nontypical="" house="12"/>
                </Organization>
                <PrivatePerson>
                    <Name Surname="" Firstname="" Fathername=""/>
                    <Econtact type=""/>
                    <Address street="" settlement="" postcode="" postbox="" flat="" district="" region="" country="" nontypical="" house=""/>
                    <SignDate/>
                    <Rank privilege="" socialposition="" sex=""/>
                </PrivatePerson>
            </Author>
            <Validator attestation="0">
                <DocNumber kind="наказ">
                    <RegNumber RegPoint="" regdate="2001-12-17T09:30:47Z"/>
                    <Organization fullname="" shortname="" ownership="" ogrn="14725836" inn="">
                        <Econtact type="Рї">kmu@test.com</Econtact>
                        <Address street="" settlement="" postcode="" postbox="" flat="" district="" region="" country="" nontypical="" house=""/>
                    </Organization>
                </DocNumber>
                <Organization fullname="" shortname="РљРњРЈ" ownership="" ogrn="96325878" inn="">
                    <Econtact type="String">kmu@test.com</Econtact>
                    <Address street="Пушкіна" settlement="" postcode="4563" postbox="" flat="" district="" region="" country="" nontypical="" house="23"/>
                    <OfficialPerson>
                        <Name Surname="" Firstname="" Fathername=""/>
                        <Official Department="" post=""/>
                        <SignDate>2011-12-17T09:30:47Z</SignDate>
                    </OfficialPerson>
                </Organization>
                <PrivatePerson>
                    <Name Surname="" Firstname="" Fathername=""/>
                    <Econtact type=""></Econtact>
                    <Address street="" settlement="" postcode="" postbox="" flat="" district="" region="" country="" nontypical="" house=""/>
                    <SignDate></SignDate>
                    <Rank privilege="" socialposition="" sex=""/>
                </PrivatePerson>
            </Validator>
            <Addressee>
                <Referred id="" retype="">
                    <RegNumber regdate="" regpoint=""/>
                    <TaskNumber taskDate=""/>
                </Referred>
                <Organization fullname="String" shortname="" ownership="" ogrn="85236974" inn="">
                    <OfficialPerson>
                        <Name Surname="" Firstname="" Fathername=""/>
                        <Official Department="" post=""/>
                    </OfficialPerson>
                    <Econtact type="Рї">sofki@test.com</Econtact>
                    <Address street="" settlement="" postcode="" postbox="" flat="" district="" region="" country="" nontypical="" type="" house=""/>
                </Organization>
                <PrivatePerson>
                    <Name Surname="" Firstname="" Fathername=""/>
                    <Econtact type=""></Econtact>
                    <Address street="" settlement="" postcode="" postbox="" flat="" district="" region="" country="" nontypical="" house=""/>
                    <Rank privilege="" socialposition="" sex=""/>
                </PrivatePerson>
            </Addressee>
            <Writer>
                <Organization fullname="" shortname="" ownership="" ogrn="" inn="">
                    <OfficialPerson>
                        <Name Surname="" Firstname="" Fathername=""/>
                        <Econtact type=""></Econtact>
                    </OfficialPerson>
                </Organization>
                <PrivatePerson>
                    <Name Surname="" Firstname="" Fathername=""/>
                    <Econtact type=""></Econtact>
                </PrivatePerson>
            </Writer>
        </Document>

edit . 编辑 As advised i try to figure out JAXB thingy. 按照建议,我尝试找出JAXB的问题。 xjc tool generated 3 classes: ObjectFactory, package-info, XML. xjc工具生成了3个类:ObjectFactory,package-info,XML。 I found this code to create object from xml: 我发现以下代码可从xml创建对象:

public static void main(String[] args) {
        try {

            File file = new File("F:\\Untitled3.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(XML.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            XML xml = (XML) jaxbUnmarshaller.unmarshal(file);
            System.out.println(xml);

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

Is this the correct way, or i need to use ObjectFactory?: 这是正确的方法,还是我需要使用ObjectFactory?

ObjectFactory f =new ObjectFactory();
            XML xml1 = f.createXML();

How do i create object with all tags and attributes, and then create xml file from it? 如何创建具有所有标签和属性的对象,然后从中创建xml文件? Im new to java and jaxb stuff, so please bear with me. 我是Java和jaxb的新手,请耐心等待。

It is usually not meaningful or commonly useful for method letting you access nodes at certain depth. 它对于让您访问特定深度的节点的方法通常没有意义或通常没有用。 This is not only about Java, but rather the DOM spec, and I believe that's the right decision. 这不仅与Java有关,而且与DOM规范有关,我相信这是正确的决定。

People usually access nodes through one of many meaningful ways: 人们通常通过许多有意义的方式之一来访问节点:

  1. Through tag name, and tag name usually indicates the meaning of the node. 通过标签名,而标签名通常表示节点的含义。
  2. XPath - the meaning full structure of the document. XPath-文档的完整含义。
  3. Binding, for example JAXB (basically you are not dealing with XML any more but java classes) 绑定,例如JAXB(基本上,您不再处理XML,而是Java类)
  4. There is the old SAX (not DOM) and StAX (a mixture of DOM and SAX) 有旧的SAX(不是DOM)和StAX(DOM和SAX的混合物)

Look up xpath and that would be really helpful. 查找xpath,这将非常有帮助。

Use "getElementsByTagName" function again on each node to get elements by tag name. 在每个节点上再次使用“ getElementsByTagName”功能,以按标签名称获取元素。 Obviously... 明显...

Here's my sample code that goes few levels deep: 这是我的示例代码,深入了几个层次:

DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(acpFile);
        Element docEle = doc.getDocumentElement();
        NodeList series = docEle.getElementsByTagName("dod:recordSeries");

        if(series != null && series.getLength()>0) 
        {
            for(int i=0; i<series.getLength(); i++) 
            {
                Element serie = (Element)series.item(i);
                System.out.println("S -- "+serie.getAttribute("view:childName"));
                NodeList categories = serie.getElementsByTagName("dod:recordCategory");

                for(int j=0; j<categories.getLength(); j++)
                {
                    Element category = (Element)categories.item(j);
                    System.out.println("C ---- "+category.getAttribute("view:childName"));
                    NodeList recordFolders = category.getElementsByTagName("rma:recordFolder");

                    for(int k=0; k<recordFolders.getLength(); k++)
                    {
                        Element folder = (Element)recordFolders.item(k);
                        System.out.println("F ------ "+folder.getAttribute("view:childName"));
                    }
                }
            }
        }

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

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