美好的一天。
我上课了:
public class XmlModifier {
private DocumentBuilderFactory docFactory = null;
private DocumentBuilder docBuilder = null;
private Document document = null;
private TransformerFactory transformFactory = null;
private Transformer transform = null;
private DOMSource source = null;
private StreamResult streamRes = null;
private boolean exepDocBuilderAlarm = true;
public XmlModifier() {
this.docFactory = DocumentBuilderFactory.newInstance();
try {
this.docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
this.exepDocBuilderAlarm = false;
e.printStackTrace();
}
}
public void prepareXMLMessage(File file, String userName, String userPassword, String reqId, Integer NUMBER_OF_MSG_SENDS) {
if (exepDocBuilderAlarm != false) {
try {
document = docBuilder.parse(file);
setElementValues("si:sourceInfo", addElementsToArray("si:reqId,si:reqTag"), addElementsToArray(reqId + "," + reqId), NUMBER_OF_MSG_SENDS);
setElementValues("usr:user", addElementsToArray("usr:id,usr:password"), addElementsToArray(userName + "," + userPassword), NUMBER_OF_MSG_SENDS);
setElementValues("meth:method", addElementsToArray("meth:id,meth:tag"), addElementsToArray(reqId + "," + reqId), NUMBER_OF_MSG_SENDS);
setElementValues("tb:tradeField", addElementsToArray("tb:value"), addElementsToArray(reqId), NUMBER_OF_MSG_SENDS);
this.transformFactory = TransformerFactory.newInstance();
this.transform = transformFactory.newTransformer();
this.source = new DOMSource(document);
this.streamRes = new StreamResult(file);
this.transform.transform(source, streamRes);
System.out.println("Done to execute XmlModifier");
} catch (Exception e) {
e.printStackTrace();
} finally {
this.docFactory = null;
this.docBuilder = null;
this.transformFactory = null;
this.transform = null;
this.source = null;
this.streamRes = null;
}
}
}
private void setElementValues(String rootElement, String[] childElements, String[] childElementsValues, Integer msgIDIncrement) {
Node nodeRootElement = document.getElementsByTagName(rootElement).item(0);
NodeList childElementlist = nodeRootElement.getChildNodes();
for (int i = 0; i < childElements.length; i++) {
for (int z = 0; z < childElementlist.getLength(); z++) {
Node node = childElementlist.item(z);
if (childElements[i].equals(node.getNodeName())) {
node.setTextContent(childElementsValues[i]);
}
}
}
}
private String[] addElementsToArray(String elements) {
String[] theArray = null;
theArray = elements.split(",");
return theArray;
}
}
在输入时我有xml,有时候形成不好。 DOM解析器的问题在于我的观点是DOM解析器从开始解析整个xml,我有像< > & " '
这样的特殊符号对我不好。
如何输入prepareXMLMessage(..)
为xml提供< > & " '
,然后在prepareXMLMessage(..)中解析它没有问题(更改元素中的一些值),而不是作为输出提供xml { {1}}返回???
感谢您的帮助。