我有一堆 XML 文档,其中包含我需要用假数据替换的个人信息。Person 节点包含以下元素:
- uuid - 必需,不应触碰。
- 名字 - 可选
- 姓氏 - 可选
- 地址 - 可选
- personID - 必填
一个人可能出现多次,在这种情况下应该使用相同的假数据,即如果两个 Person 节点具有相同的 personID,那么它们都应该收到相同的假 ID。
我已经实现了一些 Java 代码,它从 XML 字符串构建 DOM 树并在将其写回字符串之前替换节点。这很好用,但由于我有这么多文件,我想知道是否有更快的方法。也许通过正则表达式或 XSLT 之类的?
这是一个示例文档:
<ADocument>
<Stuff>
...
</Stuff>
<OtherStuff>
...
</OtherStuff>
<Person>
<uuid>11111111-1111-1111-1111-111111111111</uuid>
<firstName>Some</firstName>
<lastName>Person</lastName>
<personID>111111111111</personID>
</Person>
<Person>
<uuid>22222222-2222-2222-2222-222222222222</uuid>
<firstName>Another Person</firstName>
<address>Main St. 2</address>
<personID>222222222222</personID>
</Person>
<Person>
<uuid>33333333-3333-3333-3333-333333333333</uuid>
<firstName>Some</firstName>
<lastName>Person</lastName>
<personID>111111111111</personID>
</Person>
<MoreStuff>
...
</MoreStuff>
</ADocument>
这是我目前的实现:
public String replaceWithFalseData(String xmlInstance) {
Document dom = toDOM(xmlInstance);
XPathExpression xPathExpression = XPathExpressionFactory.createXPathExpression("//Person");
List<Node> nodeList = xPathExpression.evaluateAsNodeList(dom);
for(Node personNode : nodeList) {
Map<String, Node> childNodes = getChildNodes(personNode);
String personID = childNodes.get("personID").getTextContent();
// Retrieve a cached fake person using the ID, or create a new one if none exists.
Person fakePerson = getFakePerson(personID);
setIfExists(childNodes.get("firstName"), fakePerson.getFirstName());
setIfExists(childNodes.get("lastName"), fakePerson.getLastName());
setIfExists(childNodes.get("address"), fakePerson.getAddress());
setIfExists(childNodes.get("personID"), fakePerson.getPersonID());
}
return toString(dom);
}
public Map<String, Node> getChildNodes(Node parent) {
Map<String, Node> childNodes = new HashMap<String, Node>();
for(Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
if(child.getLocalName() != null) {
childNodes.put(child.getLocalName(), child);
}
}
return childNodes;
}
public void setIfExists(Node node, String value) {
if(node != null) {
node.setTextContent(value);
}
}