如何使用java代码在xml标记中获取值

时间:2022-11-27 17:15:10

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 =“ abcd 22 male ”;

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

参考

#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

参考