あなたは実際に続けるためにそれほど多くの文脈を与えていません。プログラミング言語、使用しているXML解析モデル、および特定の要素に属性が必要かどうかを判断するために必要なコンテキストの量。
したがって、次の1つのアプローチがあります。
- Javaを想定
- DOMアプローチに少し似た抽象的な概念的なオブジェクトのセット(ElementおよびXMLDocument)を使用します-XMLツリー内のノードに対する実際のインターフェイスを置き換えます
- 要素マッチングロジックは自己完結型であると想定しています。つまり、ロジックは、要素自体の名前またはその他の属性に基づいて特定の属性を適用する必要があるかどうかを判断でき、親、子、または祖先について知る必要はありません。
ちなみに、このコードはコンパイルおよびテストされていません。これは、アプローチの単なる例示です。
public interface ElementManipulator {
public void manipulateElement(Element elem);
}
public class AManipulator implements ElementManipulator {
public void manipulateElement(Element elem) {
if (elem.name == "something-A-cares-about") {
//add A's attribute(s) to elem
}
}
}
public class BManipulator implements ElementManipulator {
public void manipulateElement(Element elem) {
if (elem.name == "something-B-cares-about") {
//add B's attribute(s) to elem
}
}
}
public class XMLManipulator {
ArrayList<? extends ElementManipulator> manipulators;
public XMLManipulator () {
this.manipulators = new ArrayList<? extends ElementManipulator>();
this.manipulators.add(new AManipulator());
this.manipulators.add(new BManipulator());
}
public void manipulateXMLDocument(XMLDocument doc) {
Element rootElement = doc.getRootElement();
this.manipulateXMLElement(rootElement);
}
/**
* Give the provided element, and all of it's children, recursively,
* to all of the manipulators on the list.
*/
public void manipulateXMLElement(Element elem) {
foreach (ElementManipulator manipulator : manipulators) {
manipulator.manipulateElement(elem);
}
ArrayList<Element> children = elem.getChildren();
foreach(Element child: children) {
this.manipulateXMLElement(child);
}
}
}