我有一个 xml 文件,包含动态生成的标签,如下所示,
<ABC>
<XYZ>
<PQR DURI="http://try.org/claims">
<LMN>
<URI>http://yyyy/givenname</ClaimURI>
<DName>First Name</DisplayName>
<FoundationName>givenName</FoundationName>
<Description>First Name</Description>
<Required />
<DisplayOrder>1</DisplayOrder>
<SuppDefault />
</LMN>
<LMN>
<CURI>http://kkkk/nickname</ClaimURI>
<DisplayN>Nick Name</DisplayName>
<AttributeID>nickName</AttributeID>
<SDA>23edded<SDA>
<Description>Nick Name</Description>
<Required />
<DisplayOrder>2</DisplayOrder>
<TransitNumber>89393</TransitNumber>
</LMN>
</PQR>
</XYZ>
</ABC>
我想读取上面的 xml 格式并将它们添加到 Map<String,String>
作为键/值对,分别是标签名称和值。我不知道 <LMN>
之间的标签名称标签,因为它们是动态添加的。有没有可能的方法来做到这一点。
我尝试使用以下代码,
Root = element.getFirstChildWithName(new QName(XYZ)
OMElement IteratorOne = Root.getChildrenWithLocalName(PQR)
Iterator<OMElement> IteratorTwo = dialect.getChildrenWithLocalName(LMN);
while (IteratorTwo.hasNext()) {
Element = IteratorTwo.next();
Iterator iterator = Element.getChildren();
while (iterator.hasNext()) {
iterator.next();
}
}
最佳答案
我有人为其中一项工作做了这个。我使用了 dom 解析器来做到这一点。这是我稍微修改了一下以适合您的使用的代码摘录。我假设代码中 myString 包含您的 XML 文本。如果您有可用的流,则可以直接在 dBuilder 中使用它。
InputStream is = new ByteArrayInputStream(myString.getBytes());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("LMN");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
Map<String, String> map = new HashMap<String, String>();
convertNodeToMap(nNode, map);
}
这是convertNodeToMap的代码
public static void convertNodeToMap(Node node, Map<String, String> map) {
if (node != null) {
if (node.hasChildNodes()) {
NodeList list = node.getChildNodes();
for (int count = 0; count < list.getLength(); count++) {
map.put(list.item(count).getNodeName(), list.item(count).getTextContent());
}
}
}
}
如果输入文档大小相对较大,您必须意识到 DOM 解析可能会变慢。
关于Java:在不使用 QName 的情况下读取具有动态添加元素的 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31006931/