在xml文件中查找字符串并将其值分配给另一个String

时间:2013-11-21 07:56:21

标签: java

我有下面的plist。

    <?xml version="1.5" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//PSect//ACD PLIST 1.5//" "http://pset.com/ACD/plist.dtd">
<plist version="1.5">
<dict>
        <key>City</key>
        <string>Melbourne</string>
        <key>DetailedInfo</key>
        <dict>
                <key>Name</key>
                <real>Sam</real>
                <key>Income</key>
                <real>4000</real>
        </dict>
        <key>Status</key>
        <string>Single</string>
        <key>PIN</key>
        <string>123456789</string>
</dict>

我有代码将此plist解析为xml文件。我需要帮助的是找到plist中的关键城市。我查看了一些帖子来搜索xml文件中的字符串,但运气不好。基本上我想做的是,

1. Check if my xml file has Key City
2. If it does, assign its value (Melbourne) to another String. 

无论如何我能做到这一点吗?请建议。

3 个答案:

答案 0 :(得分:1)

我不确定你的plist中的doctype但尝试这个 试试这个

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) throws Exception {

        String keyVal = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(new File("input.xml"));
        NodeList keyList = document.getElementsByTagName("key");

        if(keyList !=null && keyList.getLength() > 0) {
            for(int i =0; i< keyList.getLength(); i++) {
                keyVal = keyList.item(i).getTextContent();
                if ("City".equals(keyVal)) {
                    NodeList stringList = document.getElementsByTagName("string");
                    if(stringList !=null && stringList.getLength() > 0) {
                        System.out.println(stringList.item(i).getTextContent());
                    }
                }
            }
        }
    }
}

答案 1 :(得分:1)

    XPath path = XPathFactory.newInstance().newXPath();
    NodeList nl = (NodeList) path.evaluate("//dict[key/text()='City']", doc, XPathConstants.NODESET);
    if (nl.getLength() == 1) {
        Element dictElement = (Element) nl.item(0);

        NodeList stringNodeList = dictElement.getElementsByTagName("string");
        for (int i = 0; i < stringNodeList.getLength(); i++) {
            // replace string here
            System.out.println("Replace: " + stringNodeList.item(i));
        }
    }

答案 2 :(得分:0)

为什么不使用像jaxb或xtream这样的object-xml绑定框架来执行此操作。这些框架会从你的xml中创建一个对象,然后很容易导航这个xml。例如你可以做if(“City”.equals(getDict()。getKey()){then do this}