簡體   English   中英

如何正確創建自定義XML元素?

[英]How to properly create custom XML elements?

我最近正在開發一個Weather Application,我希望將每個客戶搜索都保存為.xml格式的文件。 請參閱此處的GUI設計。

我在Java上使用以下代碼在.xml文件中寫入所需的元素,但問題是我無法追加下一個搜索並保存新的搜索,如下所示:

<search>...NEW ELEMENTS (NEW SEARCH)...</seach>

當我單擊“ ForeCast”按鈕時。

WeatherParser.java:

public void writeOnXML(String date, String[] term, String found, String geoNameID){

    try {
        XMLOutputFactory xMLOutputFactory = XMLOutputFactory.newFactory();
        XMLStreamWriter xMLStreamWriter;
        xMLStreamWriter = xMLOutputFactory
            .createXMLStreamWriter(new FileOutputStream
                ("src\\main\\java\\stax\\weatherSearches.xml"));
        //Create <weatherSearches></weatherSearches> (in weatherSearches.xml)
        xMLStreamWriter.writeStartElement("weathersearches");

            //Create <search></search> (weatherSearches.xml)
            xMLStreamWriter.writeStartElement("search");
            xMLStreamWriter.writeAttribute("date", date);

                //Create <search><term>...</term></search> (weatherSearches.xml)
                xMLStreamWriter.writeStartElement("term");
                    xMLStreamWriter.writeStartElement("temperature");
                    xMLStreamWriter.writeCharacters(term[0]);
                    xMLStreamWriter.writeEndElement(); //Close <Temperature>
                    xMLStreamWriter.writeStartElement("windDirection");
                    xMLStreamWriter.writeCharacters(term[1]);
                    xMLStreamWriter.writeEndElement(); //Close <WindDirection>
                    xMLStreamWriter.writeStartElement("windSpeed");
                    xMLStreamWriter.writeCharacters(term[2]);
                    xMLStreamWriter.writeEndElement(); //Close <WindSpeed>
                    xMLStreamWriter.writeStartElement("humidity");
                    xMLStreamWriter.writeCharacters(term[3]);
                    xMLStreamWriter.writeEndElement(); //Close <Humidity>
                    xMLStreamWriter.writeStartElement("pressure");
                    xMLStreamWriter.writeCharacters(term[4]);
                    xMLStreamWriter.writeEndElement(); //Close <Pressure>
                    xMLStreamWriter.writeStartElement("visibility");
                    xMLStreamWriter.writeCharacters(term[5]);
                    xMLStreamWriter.writeEndElement(); //Close <Visibility>
                xMLStreamWriter.writeEndElement(); //close <term>

                //Create <search><found></found></search> (weatherSearches.xml)
                xMLStreamWriter.writeStartElement("found");
                xMLStreamWriter.writeCharacters(found);
                xMLStreamWriter.writeEndElement(); //Close <found>

                //Create <search><geoNameID></geoNameID></search> (weatherSearches.xml)
                xMLStreamWriter.writeStartElement("geoNameID");
                xMLStreamWriter.writeCharacters(geoNameID);
                xMLStreamWriter.writeEndElement(); //Close <geoNameID>

            //Create <search></search> (weatherSearches.xml)
            xMLStreamWriter.writeEndElement(); //Close <search>

        xMLStreamWriter.writeEndElement(); //Close <weathersearches>

        //xMLStreamWriter.flush();;
        xMLStreamWriter.close();

    } 
    catch (FileNotFoundException ex) {
        loadErrorException(ex);
    } 
    catch (XMLStreamException ex) {
        loadErrorException(ex);
    }       
}

weatherSearches.xml:

<weathersearches>
<search date="Saturday - 14:00">
    <term>
        <temperature>11�C (52�F)</temperature>
        <windDirection>Southerly</windDirection>
        <windSpeed>18mph</windSpeed>
        <humidity>97%</humidity>
        <pressure>988mb</pressure>
        <visibility>Poor</visibility>
    </term>
    <found>true</found>
    <geoNameID>2656397</geoNameID>
</search>
</weathersearches>

另外,元素<weathersearches><search><term><temperature>的未知符號是否會引起我任何錯誤,還是應該從那里刪除它?

首先,您的所有輸出看起來都不是有效的xml,它應具有以下格式,其中

  1. 標頭告訴編碼為UTF-8,它將處理您的特殊字符
  2. 使用DocumentBuilderFactory編寫xml
 <?xml version="1.0" encoding="UTF-8" standalone="no"?> <Employees xmlns="https://www.journaldev.com/employee"> <Employee id="1"> <name>Pankaj</name> <age>29</age> <role>Java Developer</role> <gender>Male</gender> </Employee> <Employee id="2"> <name>Lisa</name> <age>35</age> <role>Manager</role> <gender>Female</gender> </Employee> </Employees> 

嘗試使用此代碼,這將生成一個有效的xml。

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;


public class XMLWriterDOM {

    public static void main(String[] args) {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.newDocument();
            //add elements to Document
            Element rootElement =
                doc.createElementNS("https://www.journaldev.com/employee", "Employees");
            //append root element to document
            doc.appendChild(rootElement);

            //append first child element to root element
            rootElement.appendChild(getEmployee(doc, "1", "Pankaj", "29", "Java Developer", "Male"));

            //append second child
            rootElement.appendChild(getEmployee(doc, "2", "Lisa", "35", "Manager", "Female"));

            //for output to file, console
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            //for pretty print
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);

            //write to console or file
            StreamResult console = new StreamResult(System.out);
            StreamResult file = new StreamResult(new File("/Users/pankaj/emps.xml"));

            //write data
            transformer.transform(source, console);
            transformer.transform(source, file);
            System.out.println("DONE");

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


    private static Node getEmployee(Document doc, String id, String name, String age, String role,
            String gender) {
        Element employee = doc.createElement("Employee");

        //set id attribute
        employee.setAttribute("id", id);

        //create name element
        employee.appendChild(getEmployeeElements(doc, employee, "name", name));

        //create age element
        employee.appendChild(getEmployeeElements(doc, employee, "age", age));

        //create role element
        employee.appendChild(getEmployeeElements(doc, employee, "role", role));

        //create gender element
        employee.appendChild(getEmployeeElements(doc, employee, "gender", gender));

        return employee;
    }


    //utility method to create text node
    private static Node getEmployeeElements(Document doc, Element element, String name, String value) {
        Element node = doc.createElement(name);
        node.appendChild(doc.createTextNode(value));
        return node;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM