1

我正在编写一个带有将数据保存到 XML 的方法的 Java 应用程序。

这是我的代码:

private void SaveToXML(String strCity, String strDate, String strforecast, String strminDegrees, String FileName)
{
    try 
    {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("Weather");
    doc.appendChild(rootElement);

    Element weatherElement = doc.createElement(strCity);
    rootElement.appendChild(weatherElement);

    Element dateElement = doc.createElement("Date");
    weatherElement.appendChild(dateElement);

    Attr attr = doc.createAttribute("id");
    attr.setValue(strDate);
    dateElement.setAttributeNode(attr);

    Element forecast = doc.createElement("forecast");
    forecast.appendChild(doc.createTextNode(strforecast));
    dateElement.appendChild(forecast);

    Element mindegrees = doc.createElement("mindegrees");
    mindegrees.appendChild(doc.createTextNode(strminDegrees));
    dateElement.appendChild(mindegrees);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(FileName));

    transformer.transform(source, result);

   } catch (ParserConfigurationException pce) {
    pce.printStackTrace();
  } catch (TransformerException tfe) {
    tfe.printStackTrace();
  }    
}        

方法调用:

SaveToXML("Auckland", "24-05-2013", "Fine", "10", "Test.xml");

这是输出的 XML 数据:

<?xml version="1.0" encoding="UTF-8"?>
<Weather>
    <Auckland>
        <Date id="24-05-2013">
            <forecast>Fine</forecast>
            <mindegrees>10</mindegrees>
        </Date>
    </Auckland>
</Weather>

能否请我帮忙修改代码,以便在调用方法时将数据附加到文档中的正确元素中。

例如,如果在奥克兰市第二次调用该方法,则天气详细信息将放置在奥克兰元素中。如果 City 作为文档中尚未包含的参数传递,则将为该 City 创建一个新元素。

更新2

这是我当前执行错误的代码:

private void SaveToXML(String strCity, String strDate, String strforecast, String strminDegrees, String FileName)
{
    try 
    {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    //Document doc = docBuilder.newDocument();
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(FileName));
    Element rootElement = doc.createElement("Weather");
    doc.appendChild(rootElement);

    NodeList weatherNodes = rootElement.getElementsByTagName(strCity);// do we already have node?
    Element weatherElement;
      if(weatherNodes.getLength() > 0){                     // if so reuse
        weatherElement = (Element) weatherNodes.item(0);
        System.out.println("Found");
    }else {                                               // else create
        weatherElement = doc.createElement(strCity);
        rootElement.appendChild(weatherElement);    
    }

    Element dateElement = doc.createElement("Date");
    weatherElement.appendChild(dateElement);

    Attr attr = doc.createAttribute("id");
    attr.setValue(strDate);
    dateElement.setAttributeNode(attr);

    Element forecast = doc.createElement("forecast");
    forecast.appendChild(doc.createTextNode(strforecast));
    dateElement.appendChild(forecast);

    Element mindegrees = doc.createElement("mindegrees");
    mindegrees.appendChild(doc.createTextNode(strminDegrees));
    dateElement.appendChild(mindegrees);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(FileName));

    transformer.transform(source, result);

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

上面的代码在运行时会产生这个错误:

[致命错误] Test.xml:1:177:文档中根元素之后的标记必须格式正确。org.xml.sax.SAXParseException:文档中根元素之后的标记必须格式正确。

更新3

这是有效的代码:

private void SaveToXML(String strCity, String strDate, String strforecast, String strminDegrees, String FileName)
{
    try 
    {

    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc;
    File file = new File(FileName);
    if (!file.exists()) {
        doc = docBuilder.newDocument();
        doc.appendChild(doc.createElement("Weather"));
    } else {
        doc = docBuilder.parse(new File(FileName));
    }

    Element rootElement = doc.getDocumentElement();
    Element weatherElement;
    NodeList weatherNodes = doc.getDocumentElement().getElementsByTagName(strCity);
    if (weatherNodes.getLength() > 0) {
        weatherElement = (Element) weatherNodes.item(0);
    } else {
        weatherElement = doc.createElement(strCity);
        rootElement.appendChild(weatherElement); 
    }

    Element dateElement = doc.createElement("Date");
    weatherElement.appendChild(dateElement);

    Attr attr = doc.createAttribute("id");
    attr.setValue(strDate);
    dateElement.setAttributeNode(attr);

    Element forecast = doc.createElement("forecast");
    forecast.appendChild(doc.createTextNode(strforecast));
    dateElement.appendChild(forecast);

    Element mindegrees = doc.createElement("mindegrees");
    mindegrees.appendChild(doc.createTextNode(strminDegrees));
    dateElement.appendChild(mindegrees);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(FileName));

    transformer.transform(source, result);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}       
4

2 回答 2

0

要修改更新 DOM 文档结构的方式,

调整

Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Weather");
doc.appendChild(rootElement);

Element weatherElement = doc.createElement(strCity);
rootElement.appendChild(weatherElement);

Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Weather");
doc.appendChild(rootElement);

  NodeList weatherNodes = rootElement.getElementsByTagName(strCity);// do we already have node?
  Element weatherElement;
  if(weatherNodes.getLength() > 0){                     // if so reuse
    weatherElement = (Element) weatherNodes.item(0);
}else {                                               // else create
    weatherElement = doc.createElement(strCity);
    rootElement.appendChild(weatherElement);    
}

请注意,DOM 确实适用于小型文档,如果它变得非常大,您将需要查看诸如 STaX 之类的东西。

于 2013-05-24T01:34:31.253 回答
0

如果 XML 文件已经存在,您应该解析它并更新城市(如果它已经存在)或添加其他内容。然后重写XML。

    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc;
    File file = new File(FileName);
    if (!file.exists()) {
        doc = docBuilder.newDocument();
        doc.appendChild(doc.createElement("Weather"));
    } else {
        doc = docBuilder.parse(file);
    }

    Element rootElement = doc.getDocumentElement();
    Element weatherElement = createWeatherElement(strCity, strDate, strforecast, strminDegrees, doc);
    NodeList weatherNodes = doc.getDocumentElement().getElementsByTagName(strCity);
    if (weatherNodes.getLength() > 0) {
        rootElement.replaceChild(weatherElement, weatherNodes.item(0));
    } else {
        rootElement.appendChild(weatherElement);
    }

    Transformer transformer = transformerFactory.newTransformer();
    ...

private Element createWeatherElement(String strCity, String strDate, String strforecast, String strminDegrees, Document doc) {
    Element rootElement = doc.getDocumentElement();
    Element weatherElement = doc.createElement(strCity);
              ...
    return weatherElement;
}
于 2013-05-24T02:09:28.330 回答