gpt4 book ai didi

java - 使用 Commons Digester 解析成 HashMap

转载 作者:行者123 更新时间:2023-12-02 00:54:20 24 4
gpt4 key购买 nike

我需要将 xml 解析为 HashMap,其中“键”是两个元素属性的串联。xml 看起来像:

<map>
<parent key='p1'><child key='c1'> value1</child></parent>
<parent key='p2'><child key='c2'> value1</child></parent>
</map>

在 map 的第一个条目中,我想将“p1.c1”作为 map 键,而“value1”作为 map 值。如何实现这一目标?

最佳答案

使用 Xstream ( http://x-stream.github.io/ ) 的示例。它不完全遵循您的 XML 规范,我添加了嵌套 <value>标签到<child>标签。

输出:

<map>
<parent key="p1">
<child key="c1">
<value>value1</value>
</child>
</parent>
<parent key="p2">
<child key="c2">
<value>value1</value>
</child>
</parent>
</map>
p1.c1=value1
p2.c2=value1

这有帮助吗?否则请跟进。

import java.util.HashMap;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class MapParser {

public static void main(String[] args) {

XStream xstream = new XStream(new DomDriver());
xstream.alias("map", Map.class);
xstream.addImplicitCollection(Map.class, "parents");
xstream.alias("parent", Parent.class);
xstream.useAttributeFor(Parent.class, "key");
xstream.alias("child", Child.class);
xstream.useAttributeFor(Child.class, "key");

Map map = (Map) xstream
.fromXML("<map><parent key='p1'><child key='c1'><value>value1</value></child></parent><parent key='p2'><child key='c2'><value>value1</value></child></parent></map>");

System.out.println(xstream.toXML(map));

java.util.Map result = new HashMap();
for (Parent parent : map.getParents()) {

Child child = parent.getChild();
String key = parent.getKey() + "." + child.getKey();
result.put(key, child.getValue());
System.out.println(key + "=" + child.getValue());
}
}
}


import java.util.ArrayList;
import java.util.List;

public class Map {

private List<Parent> parents = new ArrayList<Parent>();

public void addParent(Parent parent) {
parents.add(parent);
}

public List<Parent> getParents() {
return this.parents;
}
}

public class Parent {

private String key;
private Child child;

public Parent(String key) {
this.key = key;
}

public Child getChild() {
return child;
}

public void setChild(Child child) {
this.child = child;
}

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}
}


public class Child {

private String key;
private String value;

public Child(String key) {
this.key = key;
}

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}
}

关于java - 使用 Commons Digester 解析成 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1513703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com