我是XML的新手.我想根据请求名称阅读以下XML.请帮助我如何在Java中阅读以下XML -
<?xml version="1.0"?>
    <config>
        <Request name="ValidateEmailRequest">
            <requestqueue>emailrequest</requestqueue>
            <responsequeue>emailresponse</responsequeue>
        </Request>
        <Request name="CleanEmail">
            <requestqueue>Cleanrequest</requestqueue>
            <responsequeue>Cleanresponse</responsequeue>
        </Request>
    </config>
Buh*_*ndi 62
如果您的XML是String,那么您可以执行以下操作:
String xml = ""; //Populated XML String....
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
Element rootElement = document.getDocumentElement();
如果您的XML在文件中,那么Document document将实例化如下:
Document document = builder.parse(new File("file.xml"));
在document.getDocumentElement()你的回报是文档的文档元素节点(你的情况<config>).
一旦你有了rootElement,你可以访问元素的属性(通过调用rootElement.getAttribute()方法)等.有关java的org.w3c.dom.Element的更多方法
有关java DocumentBuilder和DocumentBuilderFactory的更多信息.请记住,提供的示例创建了一个XML DOM树,因此如果您拥有巨大的XML数据,那么树可能会很大.
更新这里是一个获得元素"价值"的例子<requestqueue>
protected String getString(String tagName, Element element) {
        NodeList list = element.getElementsByTagName(tagName);
        if (list != null && list.getLength() > 0) {
            NodeList subList = list.item(0).getChildNodes();
            if (subList != null && subList.getLength() > 0) {
                return subList.item(0).getNodeValue();
            }
        }
        return null;
    }
你可以有效地称它为,
String requestQueueName = getString("requestqueue", element);
bdo*_*han 26
如果您只是想从XML中获取单个值,则可能需要使用Java的XPath库.有关示例,请参阅我对上一个问题的回答:
它看起来像:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Demo {
    public static void main(String[] args) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document dDoc = builder.parse("E:/test.xml");
            XPath xPath = XPathFactory.newInstance().newXPath();
            Node node = (Node) xPath.evaluate("/Request/@name", dDoc, XPathConstants.NODE);
            System.out.println(node.getNodeValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
yur*_*rin 21
如果您只需要从xml检索一个(第一个)值:
public static String getTagValue(String xml, String tagName){
    return xml.split("<"+tagName+">")[1].split("</"+tagName+">")[0];
}
如果你想解析整个xml文档,请使用JSoup:
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
for (Element e : doc.select("Request")) {
    System.out.println(e);
}