如何写入不同包中的xml文件

时间:2014-10-27 08:12:20

标签: java xml xml-parsing

SRC Files
    - mainPackage
        IMFL.java
        performXMLSettings.java
    - XML
        settings.xml

我试图写入位于不同包中的xml文件,如上面的包列表中所示。 我用来写入XML文件的代码如下所示:

public class performXMLSettings {

    /**
 *
 * @param xml
 * @param root
 * @param equals
 * @return String
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static String get(String xml, String root, String tag) throws ParserConfigurationException, SAXException, IOException {
    String ret = "";

    InputStream istream = performXMLSettings.class.getClass().getResourceAsStream(xml);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
org.w3c.dom.Document doc = dBuilder.parse(istream);
    doc.getDocumentElement().normalize();
    //ret = doc.getElementsByTagName(tag).item(0).getNodeValue();

    NodeList settings = doc.getElementsByTagName(root).item(0).getChildNodes();
    for(int j=0;j<settings.getLength();j++) {
        if(settings.item(j).getNodeName().equals(tag)){
            ret = settings.item(j).getTextContent();
        }
    }
    return ret;
}
/**
 *
 * @param xml
 * @param root
 * @param tag
 * @param value
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws TransformerConfigurationException
 * @throws TransformerException
 * @throws InterruptedException
 */
public static void set(String xml, String root, String tag, String value) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException, InterruptedException, URISyntaxException {

    InputStream istream = performXMLSettings.class.getClass().getResourceAsStream(xml);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
org.w3c.dom.Document doc = dBuilder.parse(istream);
    doc.getDocumentElement().normalize();
    Node rootTag = doc.getElementsByTagName(root).item(0);
    if(rootTag.hasChildNodes()) {
        NodeList nl = rootTag.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            rootTag.removeChild(nl.item(i));
        }
    }

    Element element = doc.createElement(tag);
    element.setNodeValue(value);
    rootTag.appendChild(element);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(performXMLSettings.class.getResource(xml).toURI()));
transformer.transform(source, result);
}

}

当我试图从xml文件中获取信息时,我得到了我需要的东西,但写作过程不起作用。它不会抛出任何错误,但xml文件中没有新的内容。

这就是我使用写作的方式:

performXMLSettings.set("/XML/settings.xml", "settings", "host", hst);

有人知道为什么吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

看来,我无法回写包含该软件包的jar文件,只有在我解压缩Jar,覆盖xml然后重新打包Jar时。