Листинг 4.21. Различные методы, вызываемые методом addText (ProductFormatter.java)
// Элемент е - это товар <product>
private void addID(StringBuffer sb, Element e ){
String id = e.getAttribute("id" );
sb.append("product code: ");
if( id.length()== 0 ){ sb.append("not assigned");
}
else { sb.append( id );
}
}
// element is either a <product> or <name> as child of a product
private void addProductName( StringBuffer sb, Element e){
if( !e.getNodeName().equals("name") ){
NodeList nl = e.getElementsByTagName( "name" );
e = (Element) nl.item(0);
}
sb.append( getChildrenText( e ) );
}
// element is <author> tag
private void addAuthor( StringBuffer sb, Element e){
NodeList nl = e.getElementsByTagName( "name" );
sb.append( getChildrenText( (Element) nl.item(0)) );
}
private void addArtist( StringBuffer sb, Element e){
NodeList nl = e.getElementsByTagName( "name" );
sb.append( getChildrenText((Element) nl.item(0)) );
}
// example <author> <name> Christoph Minwich</name> </author>
// known to have price
private void addPrice( StringBuffer sb, Element e ){
NodeList nl = e.getElementsByTagName( "price" );
sb.append("price ea = ");
sb.append( nl.item(0).getFirstChild().getNodeValue() );
}
Служебный метод getChildrenText, приведенный в листинге 4.22, собирает вместе текст всех дочерних узлов данного элемента.