【问题标题】:How to create model class for XML parsing which has iteration of element如何为具有元素迭代的 XML 解析创建模型类
【发布时间】:2013-09-13 10:08:49
【问题描述】:

我是 JAVA 编程初学者。我正在通过 XML 解析制作模型类。我知道有一些例子,例如:JAXB、xmapper 等。 我有一些元素有迭代的 xml 文件。如何为此 xml 创建模型类?任何帮助.. 让我们映射一些 xml:

<root a="2.2">
    <main>
      <node1>123</node1>
      <node2>123</node2>
    </main>

    <client value="1" use="true">
      <C_node1>aaa</C_node1>
      <C_node2>bbb</C_node2>
    </client>

    <client value="2" use="true">
      <C_node1>aaa</C_node1>
      <C_node2>bbb</C_node2>
    </client>

    <client value="3" use="true">
      <C_node1>aaa</C_node1>
      <C_node2>bbb</C_node2>
    </client>


    // ...
    <client value="100" use="true">
      <C_node1>aaa</C_node1>
      <C_node2>bbb</C_node2>
    </client>    

    <System>     
     <DebugFrame>0</DebugFrame>     
    </System>

</root>

我找到了http://docs.oracle.com/cd/E12840_01/wls/docs103/webserv/data_types.html。那是我想要的吗?

已编辑 这是真实的代码。我有一些编译错误。 Java版本是

java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)

这是错误信息;

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
Class has two properties of the same name "mode"
    this problem is related to the following location:
        at public java.lang.String xmlParserTest.RootTest.getMode()
        at xmlParserTest.RootTest
    this problem is related to the following location:
        at private java.lang.String xmlParserTest.RootTest.mode
        at xmlParserTest.RootTest
Class has two properties of the same name "inputFile"
    this problem is related to the following location:
        at public java.lang.String xmlParserTest.MainEntity.getInputFile()
        at xmlParserTest.MainEntity
        at private xmlParserTest.MainEntity xmlParserTest.RootTest.main
        at xmlParserTest.RootTest
    this problem is related to the following location:
        at private java.lang.String xmlParserTest.MainEntity.inputFile
        at xmlParserTest.MainEntity
        at private xmlParserTest.MainEntity xmlParserTest.RootTest.main
        at xmlParserTest.RootTest

: 控制台.java

package xmlParserTest;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class console {

    public static void main(String[] args) {

       try
       {                    
          JAXBContext jc = JAXBContext.newInstance(RootTest.class);
            Unmarshaller u = jc.createUnmarshaller();

            File f = new File("Testing.xml");
            RootTest product = (RootTest) u.unmarshal(f);

            System.out.println(product.getMode());
            System.out.println(product.getMainEntity().getInputFile());
            System.out.println(product.getMainEntity().getOutputFolder());


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

}

: RootTest.java

package xmlParserTest;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Function")
public class RootTest {

    private MainEntity main;
    private String mode;            

    @XmlElement(name="Main")
    public MainEntity getMainEntity() {
     return main;
    }

    public void setMainEntity(MainEntity _main) {
     this.main = _main;
    }

    @XmlAttribute(name="mode")
    public String getMode() {
     return mode;
    }

    public void setMode(String _mode) {
      this.mode = _mode;
    }       

    public RootTest()
    {   
    }
}

:MainEntity.java

package xmlParserTest;

import javax.xml.bind.annotation.XmlElement;

public class MainEntity {

    private String inputFile;   
    private String inputType;   
    private String outputFolder;    
    private String outputType;  

    @XmlElement(name="InputFile")
    public String getInputFile() {
      return inputFile;
    }

    public void setInputFile(String _inputFile) {
      this.inputFile = _inputFile;
    }       

    public String getInputType() {
      return inputType;
    }

    public void setInputType(String _type) {
      this.inputType = _type;
    }

    @XmlElement(name="OutputFolder")
    public String getOutputFolder() {
      return outputFolder;
    }

    public void setOutputFolder(String _outputFolder) {
      this.outputFolder = _outputFolder;
    }   

    public String getOutputType() {
      return outputType;
    }

    public void setOutputType(String _type) {
      this.outputType = _type;
    }

    public MainEntity()
    {
    }   
}

:Testing.xml

<?xml version="1.0" encoding="UTF-8"?>
<Function mode="Execute">
  <Main>
    <InputFile type="string">C:\DATA\test.txt</InputFile>
    <OutputFolder type="string">C:\Test</OutputFolder>
  </Main>
</Function>

【问题讨论】:

    标签: java xml class xml-parsing


    【解决方案1】:

    如果您想使用 JAXB,首先,您需要创建主模型,如下所示:

    @XmlRootElement(name = "root")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Root {
        private MainEntity main;
        @XmlElement(name = "client")
        private List<ClientEntity> clients;
        @XmlAttribute
        private String a;
        @XmlElement(name = "System")
        private SystemEntity system;
    //getters and setters for all fields
    }
    

    然后,指定实体:

    public class MainEntity {
        private String node1;
        private String node2;
    //getters and setters for all fields
    }
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class ClientEntity {
        @XmlElement(name = "C_node1")
        private String C_node1;
        @XmlElement(name = "C_node2")
        private String C_node2;
        @XmlAttribute
        private Long value;
        @XmlAttribute
        private boolean use;
    //getters and setters for all fields
    }
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class SystemEntity {
        @XmlElement(name = "DebugFrame")
        private Long debugFrame;
    //getters and setters for all fields
    }
    

    如您所见,我们使用@XmlElement(name = "System") 为字段设置别名,并使用@XmlAttribute 从属性中读取字段。

    要使用 JAXB 解组 XML,请为您的类模型创建上下文:

    JAXBContext context = JAXBContext.newInstance(Root.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    Root root = (Root) unmarshaller.unmarshal(file);
    

    不要忘记:创建模型时,需要为要编组/解组的字段指定 getter 和 setter,并为类指定非参数构造函数。

    有关注释的更多信息您可以在此处找到: http://www.techferry.com/articles/jaxb-annotations.html

    玩得开心!:)

    【讨论】:

    • 谢谢,我有一个真实的代码。但是,我得到了一些编译错误。我猜来自Java版本。你有什么想法吗?
    • 是的。该问题与 Java 版本无关。当您为字段使用注释时,您必须选择: - 注释字段本身; - 为字段注释 setter 或 getter(仅其中一个 - 或 getter 或 setter) 默认情况下,JAXB 查找 getter/setter 注释。如果要注释字段,而不是 getter/setter,则必须在类上方使用注释 @XmlAccessorType(XmlAccessType.FIELD) 显式指定它。
    • 如果我指定注解@XmlAccessorType(XmlAccessType.FIELD),那么我有一些错误消息,例如XmlAccessType 无法解析为变量。可以吗?
    • 不行。您只需导入 javax.xml.bind.annotation.XmlAccessType.
    • 当然,我做到了。但是,我得到了一个编译错误。我只是更新真实的代码。这只是工作。
    【解决方案2】:

    使用 JAXB,您可以创建所需的 Java 类,如下所示:

    @XmlRootElement(name = "main")
    public class Main {
    String node1;
    String node1;
    //getters and setters for fields
    }
    
    @XmlRootElement(name = "client")
    public class Client {
    String node1;
    String node1;
    
    @XmlAttribute
    private boolean use;
    @XmlAttribute
    private int value;
    //getters and setters for fields
    }
    

    然后创建一个Root 类来表示您的 XML 文件:

    @XmlRootElement(name = "root")
    public class Root {
    //add a list of client instances
    @XmlElement(name = "client")
    private List<Client> clientList;
    //add an instance of main
    @XmlElement(name = "main")
    private Main main;
    // setters to set the values for main and clients
    }
    

    现在,通过这些代码行,您可以为 Root 类创建 XML 表示:

    Root root = new Root();
    
    root.setMain(CREATE_AND_SET_AN_INSTANCE_OF_MAIN);
    root.setClientList(CREATE_AND_SET_A_LIST_OF_CLIENTS);
    
    String filePath = "PATH_TO_SAVE_YOUR_FILE";
    File file = new File(filePath);
    JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    
    
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    
    jaxbMarshaller.marshal(alpha, file);
    

    您可以使用这些代码行将 XML 读回 Java 对象:

    String filePath = "XML_FILE_PATH";
    File file = new File(filePath);
    JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
    
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Root root = (Root) jaxbUnmarshaller.unmarshal(file);
    

    参考:Java Architecture for XML Binding (JAXB)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多