English 中文(简体)
j
原标题:Reading and writing an xml in java
  • 时间:2012-04-24 13:40:59
  •  标签:
  • java
  • dom
  • stax

我正在使用Stax parser阅读XML文件,并在java用DOM书写。 我没有获得理想的XML产出。 I 改为XML。

<config>

    <Sensor1>
       <name>abc</name>
       <range>100</range>
    </Sensor1>

   <sensor2>
       <name>xyz</name>
       <range>100</range>
   </sensor2>

</config>

I parse the above XML file using Stax parser as follows

public void readConfig(String configFile) {
boolean sensor1 = false;
boolean sensor2 = false;

try
{
  XMLInputFactory inputFactory = XMLInputFactory.newInstance();
  InputStream in = new FileInputStream(configFile);
  XMLEventReader eventReader = inputFactory.createXMLEventReader(in);

  // Read the XML document
 while (eventReader.hasNext()) {
    XMLEvent event = eventReader.nextEvent();

    if (event.isStartElement()) {

         StartElement startElement = event.asStartElement();

                if (startElement.getName().getLocalPart() == (sensor1)) {

                   sensor1 = true;
                   Sensor1 Obj1 = new Sensor1();                         
        }

            if (startElement.getName().getLocalPart() == (sensor2)) {

                        sensor2 = true;
                        Sensor2 Obj2 = new Sensor2();

                }



     if (sensor1) {

      if (event.asStartElement().getName().getLocalPart().equals(name)) {

             event = eventReader.nextEvent();
                     Obj1.set_Sensor_Name(event.asCharacters().getData());
             continue;
         }


      if (event.asStartElement().getName().getLocalPart().equals(range)) {

             event = eventReader.nextEvent();
                     Obj1.set_Sensor_Range(event.asCharacters().getData());
             continue;
         }
     }


 if (sensor2) {

   if (event.asStartElement().getName().getLocalPart().equals(name)) {
             event = eventReader.nextEvent();
             Obj2.set_Sensor_Name(event.asCharacters().getData());
             continue;
       }

       if (event.asStartElement().getName().getLocalPart().equals(range)) {

             event = eventReader.nextEvent();
                     Obj1.set_Sensor_Range(event.asCharacters().getData());
             continue;
         }


  }

 if (event.isEndElement()) {
        EndElement endElement = event.asEndElement();     
        if (endElement.getName().getLocalPart() == (sensor1)) {

                   sensor1.addToArray();
         }

        if (endElement.getName().getLocalPart() == (sensor2)) {

                    sensor2.addToArray();

        }
       }
     }

在“Sensor1”和“Sensor2”类中,我根据某些条件增加了额外信息。

class Sensor1 {

  public ArrayList<Object> list = new ArrayList<Object>();
  String name;
  double range;

  public void set_Sensor_Name(String name) {
  this.name = name;

  }

  public void set_Sensor_Range(double range) {
  this.range = range;

  }

  public void addToArray(){
    double distance =50;

     if(distance<range){
       list.add("TITANIC");
       list.add(123456);
     }

     WriteFile fileObj = new WriteFile();
     fileObj.writeXMlFile(list);

  }

} 

这是写XML的班子。

public class WriteFile {

public void writeXmlFile(ArrayList<Object> list) {

try {

    DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
    DocumentBuilder build = dFact.newDocumentBuilder();
    Document doc = build.newDocument();

    Element root = doc.createElement("SensorTracks");
    doc.appendChild(root);

    Element sensorInfo = doc.createElement("SensorDetails");
    root.appendChild(sensorInfo);

    Element vesselInfo = doc.createElement("VesselDetails");
    root.appendChild(vesselInfo);


    for(int i=0; i<list.size(); i +=4 ) {

        Element name = doc.createElement("SensorName");
        name.appendChild(doc.createTextNode(String.valueOf(list.get(i))));
        sensorInfo.appendChild(name);

        Element range = doc.createElement("SensorRange");
        name.appendChild(doc.createTextNode(String.valueOf(list.get(i+1))));
        sensorInfo.appendChild(range);

        Element mmi = doc.createElement("shipname");
        mmi.appendChild(doc.createTextNode(String.valueOf(list.get(i+2))));
        vesselInfo.appendChild(mmi);

        Element license = doc.createElement("license");
        license.appendChild(doc.createTextNode(String.valueOf(list.get(i+3))));
        vesselInfo.appendChild(license); 

    }


     // Save the document to the disk file
    TransformerFactory tranFactory = TransformerFactory.newInstance();
    Transformer aTransformer = tranFactory.newTransformer();

    // format the XML nicely
    aTransformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");

    aTransformer.setOutputProperty(
            "{http://xml.apache.org/xslt}indent-amount", "4");
    aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");



    DOMSource source = new DOMSource(doc);
    try {
        FileWriter fos = new FileWriter("/home/ros.xml");
        StreamResult result = new StreamResult(fos);
        aTransformer.transform(source, result);

    } catch (IOException e) {

        e.printStackTrace();
    }



} catch (TransformerException ex) {
    System.out.println("Error outputting document");

} catch (ParserConfigurationException ex) {
    System.out.println("Error building document");
}

When I execute, I get following XML

<SensorTracks>        
   <sensorDetails>
     <SensorName>xyz</SensorName>
     <SensorRange>100</SensorRange>
   </sensorDetails>
 <VesselDetails>
      <shipname>TITANIC</shipname>
      <license>123456</license>
</vesselDetails>

最终结果

<config>

<SensorTracks>        
   <sensorDetails>
     <SensorName>xyz</SensorName>
     <SensorRange>100</SensorRange>
     <SensorName>abc</SensorName>
     <SensorRange>100</SensorRange> 
   </sensorDetails>
 <VesselDetails>
      <shipname>TITANIC</shipname>
      <license>123456</license>
</vesselDetails>

我在守则中做了哪些错误? 感谢任何帮助。 预 收

最佳回答

我再次回答我自己的问题。 这个问题非常简单。 取得上述预期产出。 仅对“标准”类别作如下改动。

FileWriter fos = new FileWriter("/home/ros.xml" ,true);

最后,我学习 Java:

问题回答

Frankly speaking the example looks cumbersome. Do you consider to use apache digester of jaxb?
http://commons.apache.org/digester/
http://www.oracle.com/technetwork/articles/javase/index-140168.html





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签