001/* 002 * BioJava development code 003 * 004 * This code may be freely distributed and modified under the 005 * terms of the GNU Lesser General Public Licence. This should 006 * be distributed with the code. If you do not have a copy, 007 * see: 008 * 009 * http://www.gnu.org/copyleft/lesser.html 010 * 011 * Copyright for this code is held jointly by the individual 012 * authors. These should be listed in @author doc comments. 013 * 014 * For more information on the BioJava project and its aims, 015 * or to join the biojava-l mailing list, visit the home page 016 * at: 017 * 018 * http://www.biojava.org/ 019 * 020 */ 021package org.biojava.nbio.protmod.io; 022 023import org.biojava.nbio.protmod.structure.StructureAtom; 024import org.biojava.nbio.protmod.structure.StructureGroup; 025import org.biojava.nbio.core.util.PrettyXMLWriter; 026import org.w3c.dom.NamedNodeMap; 027import org.w3c.dom.Node; 028import org.w3c.dom.NodeList; 029 030import java.io.IOException; 031import java.io.PrintWriter; 032import java.io.StringWriter; 033 034public class StructureAtomXMLConverter { 035 036 public static String toXML(StructureAtom atom) throws IOException{ 037 038 StringWriter out = new StringWriter(); 039 040 PrettyXMLWriter xml = new PrettyXMLWriter(new PrintWriter(out)); 041 toXML(atom, xml); 042 043 return out.toString(); 044 } 045 046 public static void toXML(StructureAtom atom, PrettyXMLWriter xml) throws IOException{ 047 String name = atom.getAtomName(); 048 xml.openTag("structureAtom"); 049 xml.attribute("name", name); 050 StructureGroup group = atom.getGroup(); 051 StructureGroupXMLConverter.toXML(group,xml); 052 xml.closeTag("structureAtom"); 053 } 054 055 public static StructureAtom fromXML(Node structureAtomElement){ 056 057 String name = structureAtomElement.getNodeName(); 058 if ( ! name.equals("structureAtom")) 059 throw new RuntimeException("Node is not a structureAtom, but " +name); 060 061 String atomName = getAttribute( structureAtomElement,"name"); 062 StructureGroup group = null; 063 064 NodeList valList = structureAtomElement.getChildNodes(); 065 int numChildren = valList.getLength(); 066 067 for ( int e =0; e< numChildren ; e++){ 068 Node nodes = valList.item(e); 069 070 if(!nodes.hasAttributes()) continue; 071 072 073 if ( nodes.getNodeName().equals("structureGroup")) { 074 group = StructureGroupXMLConverter.fromXML(nodes); 075 } 076 } 077 StructureAtom atom = new StructureAtom(group, atomName); 078 return atom; 079 } 080 081 private static String getAttribute(Node node, String attr){ 082 if( ! node.hasAttributes()) 083 return null; 084 085 NamedNodeMap atts = node.getAttributes(); 086 087 if ( atts == null) 088 return null; 089 090 Node att = atts.getNamedItem(attr); 091 if ( att == null) 092 return null; 093 094 String value = att.getTextContent(); 095 096 return value; 097 098 } 099 100}