使用Java获取XML标记的属性值

时间:2018-01-05 02:28:28

标签: java xml transformer

我正在尝试用Java替换text2。我在使用此代码时遇到问题:

class Dialogo(QDialog):
    def __init__(self, item):
        QDialog.__init__(self)
        uic.loadUi("menu/" + item + ".ui", self)
        if item == 'addItems':
            self.load()
            self.saveitem.clicked.connect(self.save_items)
            self.cancelbtn.clicked.connect(self.reject)

    def load(self):
        self.listitems.clear()
        items = DB.jsonOpen('items')
        for p in items:
            self.listitems.addItem(p['title'])

    def save_items(self):
        data = DB.jsonOpen('items')
        title = self.title.text()
        id = self.id.text()
        enabled = self.status.isChecked():
        data.append({
            'id': id,
            'title': title,
            'path': 'path',
            'enabled': enabled
        })
        DB.jsonSave(data, 'items')
        self.title.clear()
        self.id.clear()
        self.status.setChecked(False)
        self.listitems.addItem(title)
        # self.load()

这就是XML的样子:

try {
    String filepath = "c:\\path\\file.xml";
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.parse(filepath);
    Node a = doc.getFirstChild();
    Node b = doc.getElementsByTagName("b").item(0);
    NodeList list = b.getChildNodes();

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

               Node node = list.item(i);
       if ("c".equals(node.getNodeName())) { //Want to add '&& attribute value of key is 4'
        node.setTextContent("new text");
       }

    }

    // write the content into xml file
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(filepath));
    transformer.transform(source, result);

    System.out.println("Done");

   } catch (ParserConfigurationException pce) {
    pce.printStackTrace();
   } catch (TransformerException tfe) {
    tfe.printStackTrace();
   } catch (IOException ioe) {
    ioe.printStackTrace();
   } catch (SAXException sae) {
    sae.printStackTrace();
   }

我从这里的指南得到了这个:https://www.mkyong.com/java/how-to-modify-xml-file-in-java-dom-parser/ 并且目前还在这一行<?xml version="1.0" encoding="utf-8"> <a> <b id="1"> <c key="3">text1</c> <c key="4">text2</c> //Replace this </b> <b id="2"> <c key="5">text3</c> <c key="6">text4</c> </b> </a>

上给我一个错误

1 个答案:

答案 0 :(得分:1)

对于像这样的简单内容,您可以使用带有表达式"//c[@key='4']"的XPath,这意味着:在任何级别查找<c>元素,并使用名为key的属性,其值为{{ 1}}。

4

输出

Document doc = DocumentBuilderFactory.newInstance()
                                     .newDocumentBuilder()
                                     .parse("file.xml");

Node c4 = (Node) XPathFactory.newInstance()
                             .newXPath()
                             .evaluate("//c[@key='4']", doc, XPathConstants.NODE);
c4.setTextContent("new text");

TransformerFactory.newInstance()
                  .newTransformer()
                  .transform(new DOMSource(doc),
                             new StreamResult(System.out));