java 将java中对象的数据写入xml文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12648125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:41:46  来源:igfitidea点击:

Writing data from objects in java into a xml file

javaxml

提问by Gopal Samant

I have a piece of code as follows :

我有一段代码如下:

    Person person1 = new Person();
    person1.setName("abc");
    person1.setAge(23);

    Person person2 = new Person();
    person2.setName("xyz");
    person2.setAge(32);

And it needs to re represented in a xml file as :

它需要在 xml 文件中重新表示为:

   <Person>
       <person1>
           <name>abc</name>
           <age>23</age>
       </person1>
       <person2>
           <name>abc</name>
           <age>23</age>
       </person2>
   </Person>

How do I do it?

我该怎么做?

回答by user1635014

I guess you are looking for java-xml binding. You can JAXB binding and marshall. Please check the link http://www.mkyong.com/java/jaxb-hello-world-example/for sample.

我猜您正在寻找 java-xml 绑定。您可以通过 JAXB 绑定和编组。请查看链接 http://www.mkyong.com/java/jaxb-hello-world-example/以获取示例。

回答by Gopal Samant

checking out at the code in your link i implemented it for my code. The code is as follows. I can write xml data only for one object and if I loop it just writes the last object. So when I tried to used the file in append mode it stopped functioning :

查看您链接中的代码,我为我的代码实现了它。代码如下。我只能为一个对象编写 xml 数据,如果我循环它只写最后一个对象。因此,当我尝试在追加模式下使用该文件时,它停止运行:

try {
    FileOutputStream file = new FileOutputStream("file.xml", true);
    JAXBContext jaxbContext = JAXBContext.newInstance(NeuronNode.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    // output pretty printed
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);


    for(int i=0; i<neuronNodes.length; i++)
    {
        jaxbMarshaller.marshal(neuronNodes[i], file);
        jaxbMarshaller.marshal(neuronNodes[i], System.out);
    }

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

回答by pidabrow

You could also use Serialization and XML-Parser (DOM for example). If you create an XML document then you can use XPath for querying.

您还可以使用序列化和 XML-Parser(例如 DOM)。如果创建 XML 文档,则可以使用 XPath 进行查询。

I'd also consider on using http://simple.sourceforge.net/

我也会考虑使用http://simple.sourceforge.net/

回答by Atul Sharma

Have sorted out this problem using Hymanson Library and XMLMapper method. Here is the code for the same.

已经使用Hymanson Library 和 XMLMapper 方法解决了这个问题。这是相同的代码。

  **MainClass.java:-**

  import java.io.IOException;

  import com.fasterxml.Hymanson.databind.ObjectMapper;
  import com.fasterxml.Hymanson.databind.SerializationFeature;
  import com.fasterxml.Hymanson.dataformat.xml.XmlMapper;

   public class MainClass {

   public static void main(String[] args) throws IOException {

    String xmlString = "   <Person>\r\n" + "       <person1>\r\n" + "           
        <name>abc</name>\r\n"
            + "           <age>23</age>\r\n" + "       </person1>\r\n" + "       
        <person2>\r\n"
            + "           <name>abc</name>\r\n" + "           <age>23</age>\r\n" + "       
       </person2>\r\n"
            + "   </Person>";

    ObjectMapper xmlMapper = new XmlMapper();
    xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);

    Person1 person1 = new Person1();
    person1.setName("abc");
    person1.setAge("23");

    Person2 person2 = new Person2();
    person2.setName("xyz");
    person2.setAge("32");

    Person person = new Person();
    person.setPerson1(person1);
    person.setPerson2(person2);

    String XMLStr = xmlMapper.writeValueAsString(person);

    System.out.println(XMLStr);

} }

    **Person.java:-**

   public class Person {
    Person1 Person1Object;
    Person2 Person2Object;

// Getter Methods

public Person1 getPerson1() {
    return Person1Object;
}

public Person2 getPerson2() {
    return Person2Object;
}

// Setter Methods

public void setPerson1(Person1 person1Object) {
    this.Person1Object = person1Object;
}

public void setPerson2(Person2 person2Object) {
    this.Person2Object = person2Object;
   } }

 **Person1.java:-**
public class Person1 {
private String name;
private String age;

// Getter Methods

public String getName() {
    return name;
}

public String getAge() {
    return age;
}

// Setter Methods

public void setName(String name) {
    this.name = name;
}

public void setAge(String age) {
    this.age = age;
} }

  **Person2.java:-**

  public class Person2 {
private String name;
private String age;

// Getter Methods

public String getName() {
    return name;
}

public String getAge() {
    return age;
}

// Setter Methods

public void setName(String name) {
    this.name = name;
}

public void setAge(String age) {
    this.age = age;
} }

  **OUTPUT:-**

       <Person>
         <person1>
              <name>abc</name>
              <age>23</age>
        </person1>
         <person2>
              <name>xyz</name>
              <age>32</age>
        </person2>
      </Person>

回答by Fredrik

I have used XStreamfor this many times.

我已经多次使用XStream