我是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>
答案 0 :(得分:59)
如果您的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&amp;的更多信息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);
答案 1 :(得分:25)
如果您只想从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();
}
}
}
答案 2 :(得分: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);
}
答案 3 :(得分:4)
答案 4 :(得分:1)
有两种一般方法可以做到这一点。您将创建该XML文件的域对象模型,请查看this
,第二个选择是使用事件驱动的解析,它是DOM xml表示的替代方法。你可以找到这两种基本技术here的最佳整体比较。当然,有关处理xml的更多信息,例如,如果您获得XML模式定义(XSD),则可以使用JAXB。
答案 5 :(得分:1)
如果XML格式正确,则可以将其转换为Document。通过使用XPath,您可以获得XML元素。
String xml = "<stackusers><name>Yash</name><age>30</age></stackusers>";
表单XML字符串创建文档并使用其XML路径查找元素。
Document doc = getDocument(xml, true);
public static Document getDocument(String xmlData, boolean isXMLData) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc;
if (isXMLData) {
InputSource ips = new org.xml.sax.InputSource(new StringReader(xmlData));
doc = dBuilder.parse(ips);
} else {
doc = dBuilder.parse( new File(xmlData) );
}
return doc;
}
使用
org.apache.xpath.XPathAPI
获取Node或NodeList。
System.out.println("XPathAPI:"+getNodeValue(doc, "/stackusers/age/text()"));
NodeList nodeList = getNodeList(doc, "/stackusers");
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList));
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList.item(0)));
public static String getNodeValue(Document doc, String xpathExpression) throws Exception {
Node node = org.apache.xpath.XPathAPI.selectSingleNode(doc, xpathExpression);
String nodeValue = node.getNodeValue();
return nodeValue;
}
public static NodeList getNodeList(Document doc, String xpathExpression) throws Exception {
NodeList result = org.apache.xpath.XPathAPI.selectNodeList(doc, xpathExpression);
return result;
}
使用
javax.xml.xpath.XPathFactory
System.out.println("javax.xml.xpath.XPathFactory:"+getXPathFactoryValue(doc, "/stackusers/age"));
static XPath xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
public static String getXPathFactoryValue(Document doc, String xpathExpression) throws XPathExpressionException, TransformerException, IOException {
Node node = (Node) xpath.evaluate(xpathExpression, doc, XPathConstants.NODE);
String nodeStr = getXmlContentAsString(node);
return nodeStr;
}
使用文档元素。
System.out.println("DocumentElementText:"+getDocumentElementText(doc, "age"));
public static String getDocumentElementText(Document doc, String elementName) {
return doc.getElementsByTagName(elementName).item(0).getTextContent();
}
在两个字符串之间获取值。
String nodeVlaue = org.apache.commons.lang.StringUtils.substringBetween(xml, "<age>", "</age>");
System.out.println("StringUtils.substringBetween():"+nodeVlaue);
完整示例:
public static void main(String[] args) throws Exception {
String xml = "<stackusers><name>Yash</name><age>30</age></stackusers>";
Document doc = getDocument(xml, true);
String nodeVlaue = org.apache.commons.lang.StringUtils.substringBetween(xml, "<age>", "</age>");
System.out.println("StringUtils.substringBetween():"+nodeVlaue);
System.out.println("DocumentElementText:"+getDocumentElementText(doc, "age"));
System.out.println("javax.xml.xpath.XPathFactory:"+getXPathFactoryValue(doc, "/stackusers/age"));
System.out.println("XPathAPI:"+getNodeValue(doc, "/stackusers/age/text()"));
NodeList nodeList = getNodeList(doc, "/stackusers");
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList));
System.out.println("XPathAPI NodeList:"+ getXmlContentAsString(nodeList.item(0)));
}
public static String getXmlContentAsString(Node node) throws TransformerException, IOException {
StringBuilder stringBuilder = new StringBuilder();
NodeList childNodes = node.getChildNodes();
int length = childNodes.getLength();
for (int i = 0; i < length; i++) {
stringBuilder.append( toString(childNodes.item(i), true) );
}
return stringBuilder.toString();
}
输出:
StringUtils.substringBetween():30
DocumentElementText:30
javax.xml.xpath.XPathFactory:30
XPathAPI:30
XPathAPI NodeList:<stackusers>
<name>Yash</name>
<age>30</age>
</stackusers>
XPathAPI NodeList:<name>Yash</name><age>30</age>
答案 6 :(得分:0)
以下链接可能会有所帮助
http://labe.felk.cvut.cz/~xfaigl/mep/xml/java-xml.htm
答案 7 :(得分:0)
有各种API可用于通过Java读/写XML文件。 我会使用StaX
来引用这也很有用 - Java XML APIs
答案 8 :(得分:0)
由于您使用此配置,最好的选择是apache commons-configuration。对于简单文件,它比“原始”XML解析器更容易使用。
请参阅XML how-to
答案 9 :(得分:0)
您可以创建一个扩展org.xml.sax.helpers.DefaultHandler并调用
的类start_<tag_name>(Attributes attrs);
和
end_<tag_name>();
因为它是:
start_request_queue(attrs);
等
然后扩展该类并实现所需的xml配置文件解析器。例如:
... public void startElement(String uri, String name, String qname, org.xml.sax.Attributes attrs) throws org.xml.sax.SAXException { Class[] args = new Class[2]; args[0] = uri.getClass(); args[1] = org.xml.sax.Attributes.class; try { String mname = name.replace("-", ""); java.lang.reflect.Method m = getClass().getDeclaredMethod("start" + mname, args); m.invoke(this, new Object[] { uri, (org.xml.sax.Attributes)attrs }); }
catch (IllegalAccessException e) { throw new RuntimeException(e); }
catch (NoSuchMethodException e) { throw new RuntimeException(e); }
catch (java.lang.reflect.InvocationTargetException e) { org.xml.sax.SAXException se = new org.xml.sax.SAXException(e.getTargetException()); se.setStackTrace(e.getTargetException().getStackTrace()); }
并在特定的配置解析器中:
public void start_Request(String uri, org.xml.sax.Attributes attrs) { // make sure to read attributes correctly System.err.println("Request, name="+ attrs.getValue(0); }