如何使用 Java 检索 XML 的元素值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4076910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve element value of XML using Java?
提问by Sameek Mishra
I am new to XML. I want to read the following XML on the basis of request name. Please help me on how to read the below XML in Java -
我是 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>
采纳答案by Buhake Sindi
If your XML is a String, Then you can do the following:
如果您的 XML 是字符串,那么您可以执行以下操作:
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();
If your XML is in a file, then Document document
will be instantiated like this:
如果您的 XML 在文件中,则将Document document
像这样实例化:
Document document = builder.parse(new File("file.xml"));
The document.getDocumentElement()
returns you the node that is the document element of the document (in your case <config>
).
在document.getDocumentElement()
返回您是文档的文档元素节点(你的情况<config>
)。
Once you have a rootElement
, you can access the element's attribute (by calling rootElement.getAttribute()
method), etc. For more methods on java's org.w3c.dom.Element
一旦有了rootElement
,就可以访问元素的属性(通过调用rootElement.getAttribute()
方法)等。有关 java 的org.w3c.dom.Element 的更多方法
More info on java DocumentBuilder& DocumentBuilderFactory. Bear in mind, the example provided creates a XML DOM tree so if you have a huge XML data, the tree can be huge.
有关 java DocumentBuilder和DocumentBuilderFactory 的更多信息。请记住,提供的示例创建了一个 XML DOM 树,因此如果您有大量的 XML 数据,该树可能会很大。
- 相关问题。
UpdateHere's an example to get "value" of element <requestqueue>
更新这是获取元素“值”的示例<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;
}
You can effectively call it as,
您可以有效地将其称为,
String requestQueueName = getString("requestqueue", element);
回答by posdef
回答by Abdul Khaliq
回答by lisak
There are two general ways of doing that. You will either create a Domain Object Model of that XML file, take a look at this
有两种一般方法可以做到这一点。您将创建该 XML 文件的域对象模型,看看这个
and the second choice is using event driven parsing, which is an alternative to DOM xml representation. Imho you can find the best overall comparison of these two basic techniques here. Of course there are much more to know about processing xml, for instance if you are given XML schema definition (XSD), you could use JAXB.
第二种选择是使用事件驱动解析,这是 DOM xml 表示的替代方法。恕我直言,你可以找到的这两个基本技术的最佳整体比较这里。当然,有关处理 xml 的知识还有很多,例如,如果给定了 XML 模式定义 (XSD),则可以使用JAXB。
回答by Vishal
There are various APIs available to read/write XML files through Java. I would refer using StaX
有多种 API 可用于通过 Java 读/写 XML 文件。我会参考使用StaX
Also This can be useful - Java XML APIs
这也很有用 - Java XML APIs
回答by Bozho
Since you are using this for configuration, your best bet is apache commons-configuration. For simple files it's way easier to use than "raw" XML parsers.
由于您使用它进行配置,因此您最好的选择是 apache commons-configuration。对于简单文件,它比“原始”XML 解析器更易于使用。
See the XML how-to
请参阅XML 操作方法
回答by khachik
You can make a class which extends org.xml.sax.helpers.DefaultHandler and call
您可以创建一个扩展 org.xml.sax.helpers.DefaultHandler 的类并调用
start_<tag_name>(Attributes attrs);
and
和
end_<tag_name>();
For it is:
因为它是:
start_request_queue(attrs);
etc.
等等。
And then extends that class and implement xml configuration file parsers you want. Example:
然后扩展该类并实现您想要的 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()); }
and in a particular configuration parser:
并在特定的配置解析器中:
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); }
回答by bdoughan
If you are just looking to get a single value from the XML you may want to use Java's XPath library. For an example see my answer to a previous question:
如果您只是想从 XML 中获取单个值,您可能需要使用 Java 的 XPath 库。例如,请参阅我对上一个问题的回答:
It would look something like:
它看起来像:
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();
}
}
}
回答by yurin
In case you just need one (first) value to retrieve from xml:
如果您只需要从 xml 中检索一个(第一个)值:
public static String getTagValue(String xml, String tagName){
return xml.split("<"+tagName+">")[1].split("</"+tagName+">")[0];
}
In case you want to parse whole xml document use JSoup:
如果您想解析整个 xml 文档,请使用 JSoup:
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
for (Element e : doc.select("Request")) {
System.out.println(e);
}