I have a String variable in java with xml tags as its value:
我在java中有一个String变量,其xml标签为其值:
eg: String xml="<root><name>abcd</name><age>22</age><gender>male</gender></root>";
例如:String xml =“
Now I need to get the value within the name tag i.e "abcd" from this variable and store the value in another string variable. How to go about this using java. Can anyone please help me out with this?
现在我需要从名称标签中获取值,即从该变量中获取“abcd”,并将值存储在另一个字符串变量中。如何使用java进行此操作。有人可以帮我解决这个问题吗?
1 个解决方案
#1
1
It is not quite clear what you want, but I think what you will need is something to read an XML document (as a file or directly as a string), an XML parser.
目前还不是很清楚你想要什么,但我认为你需要的是读取XML文档(作为文件或直接作为字符串),XML解析器。
There is a whole list (and many more) of different XML parsers you can use for this:
您可以使用以下列表(以及更多)不同的XML解析器:
I would recommend dom4j for its easy usage. Here is an example for a dom4j implemenation:
我建议使用dom4j以方便使用。以下是dom4j实现的示例:
String xmlPath = "myXmlDocument.xml";
SAXReader reader = new SAXReader();
Document document = reader.read(xmlPath);
Element rootElement = document.getRootElement();
System.out.println("Root Element: "+rootElement.getName());
You can directly feed in a String to be parsed to an XML document too:
您也可以直接输入要解析为XML文档的String:
String xmlString = "<name>Hello</name>";
SAXReader reader = new SAXReader();
Document document = DocumentHelper.parseText(xmlString);
Element rootElement = document.getRootElement();
System.out.println("Root Element: "+rootElement.getName());
References
参考
-
适用于Java的最佳XML解析器
-
http://dom4j.sourceforge.net/dom4j-1.6.1/faq.html#from-string
http://dom4j.sourceforge.net/dom4j-1.6.1/faq.html#from-string
#1
1
It is not quite clear what you want, but I think what you will need is something to read an XML document (as a file or directly as a string), an XML parser.
目前还不是很清楚你想要什么,但我认为你需要的是读取XML文档(作为文件或直接作为字符串),XML解析器。
There is a whole list (and many more) of different XML parsers you can use for this:
您可以使用以下列表(以及更多)不同的XML解析器:
I would recommend dom4j for its easy usage. Here is an example for a dom4j implemenation:
我建议使用dom4j以方便使用。以下是dom4j实现的示例:
String xmlPath = "myXmlDocument.xml";
SAXReader reader = new SAXReader();
Document document = reader.read(xmlPath);
Element rootElement = document.getRootElement();
System.out.println("Root Element: "+rootElement.getName());
You can directly feed in a String to be parsed to an XML document too:
您也可以直接输入要解析为XML文档的String:
String xmlString = "<name>Hello</name>";
SAXReader reader = new SAXReader();
Document document = DocumentHelper.parseText(xmlString);
Element rootElement = document.getRootElement();
System.out.println("Root Element: "+rootElement.getName());
References
参考
-
适用于Java的最佳XML解析器
-
http://dom4j.sourceforge.net/dom4j-1.6.1/faq.html#from-string
http://dom4j.sourceforge.net/dom4j-1.6.1/faq.html#from-string