我有这个 XML:
<XmlParent>
<name>koraytugay</name>
<bar>
<baz>
<to>Tove</to>
<qux>00000001</qux>
</baz>
</bar>
<note>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
</XmlParent>
我想搜索“to”和“from”并提取该数据 XML 格式并不总是相同,但“from”和“to”将始终存在(要查找的实际节点将在属性文件中配置)
我打算这样做的方法是转换为 json 文件,所以我希望它看起来像这样
{
to:Tove
qux:00000001
from:Jani
heading:Reminder
body:Don't forget me this weekend!
}
目前我得到的是这样的
XmlParent:
{
name:koraytugay
bar:
{
baz:
{
to:Tove
qux:00000001
}
}
note:
{
from:Jani
heading:Reminder
body:Don't forget me this weekend!
}
}
}
我尝试过多种不同的方法。 我有一个看起来像这样的 XSD(从架构标记中删除了实际数据,但这工作正常)
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns=""
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns=""
targetNamespace=""
elementFormDefault="unqualified" attributeFormDefault="unqualified">
<xs:annotation>
<xs:documentation xml:lang="en">
Initial Draft
</xs:documentation>
</xs:annotation>
<xs:element name="XMLExample">
<xs:complexType>
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
这就是我现在正在做的事情
private static final Log LOGGER = LogFactory.getLog(XmlConverter.class);
public Map<String, Object> xmlStringToHashMap(String xml) {
JSON json = xmlStringToJSON(xml);
return jsonToMap(json.toString(2));
}
public Map<String, Object> jsonToMap(String jsonString) {
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, Object> jsonInMap = mapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {
});
LOGGER.info("JSON Map created: " + jsonInMap);
return jsonInMap;
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
return null;
}
public JSON xmlStringToJSON(String xml) {
XMLSerializer xmlSerializer = new XMLSerializer();
return xmlSerializer.read(xml);
}
知道如何将元素及其数据添加到一个 JSON 文件或 HashMap 中,同时忽略父标签吗?
最佳答案
我设法使用 XPath 表达式 //to/text()
这是我的解决方案:
private String[] elements;
public Map<String, Object> xPathParser(String xmlString) {
try {
Document xmlDoc = xmlStringToDocument(xmlString);
XPath xpath = XPathFactory.newInstance().newXPath();
String expression;
Map<String, Object> elements = new HashMap<>();
for (String element : elements) {
expression = MessageFormat.format("//{0}/text()", element);
Object xpathValue = xpath.compile(expression).evaluate(xmlDoc, XPathConstants.STRING);
elements.put(element, xpathValue);
}
return elements;
} catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException e) {
LOGGER.error(e.toString());
return null;
}
}
关于java - 如何将 XML 转换为 HashMap 而忽略父子关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56292120/