XML 文字列内のすべてのノードをループして値を更新しようとすると、少し問題が発生します。私はまだ Java にかなり慣れていないことに注意してください。
私の目的は、すべての要素と属性を調べてから、各値に対して正規表現を実行して、フィールドに事前定義された文字セットのみが含まれていることを確認することです。フィールドに不要な文字が含まれている場合、これらは削除され、フィールドが更新されます。
私はおそらくこれを完全に間違っていますが、子供の子供を編集しようとすると問題が発生します。以下のコードを参照してください。
protected NodeList checkXML(Node node, String strStripCharsRegEx) {
String strNodeResult = "";
//NodeList nodeResult = null;
// do something with the current node instead of System.out
System.out.println(node.getNodeName());
strNodeResult = "";
if(node.getNodeValue() != null && node.getNodeValue() != "")
{
for(char c : node.getNodeValue().toCharArray()) {
if(Character.toString(c).matches(strStripCharsRegEx))
strNodeResult = strNodeResult + c;
}
if(strNodeResult != "")
{
node.setNodeValue(strNodeResult);
}
}
if(node.hasAttributes())
{
NamedNodeMap XMLAttributes = node.getAttributes();
if(XMLAttributes != null)
{
for(int attribIndex=0; attribIndex< XMLAttributes.getLength(); attribIndex++)
{
System.out.println("AttribName = " + XMLAttributes.item(attribIndex).getNodeName());
if(XMLAttributes.item(attribIndex).getNodeValue() != null)
{
if(XMLAttributes.item(attribIndex).getNodeValue() != null && XMLAttributes.item(attribIndex).getNodeValue() != "")
{
strNodeResult = "";
for(char c : XMLAttributes.item(attribIndex).getNodeValue().toCharArray())
{
if(Character.toString(c).matches(strStripCharsRegEx))
strNodeResult = strNodeResult + c;
}
if(strNodeResult != "")
{
XMLAttributes.item(attribIndex).setNodeValue(strNodeResult);
}
}
System.out.println("AttribValue = " + XMLAttributes.item(attribIndex).getNodeValue());
}
}
}
}
//Check for Children
NodeList nodeList = node.getChildNodes();
if(nodeList != null && node.hasChildNodes())
{
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
if(currentNode.hasChildNodes())
{
//calls this method for all the children which is Element
checkXML(currentNode, strStripCharsRegEx);
}
}
}
}
return nodeList;
}
どんな助けでも大歓迎です。
ありがとう
アンディ