Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- GOTO Xml_teszt.java
- https://szit.hu/doku.php?id=oktatas:programozas:java:java_xml
- http://faragocsaba.hu/java-extlibs-xml
- https://javaoktato.com/java_2ed/chapter_jaxb.pdf
- https://labex.io/tutorials/java-how-to-access-elements-and-attributes-in-an-xml-document-with-java-413933
- https://dom4j.github.io/javadoc/2.1.4/
- */
- import java.io.*;
- import java.util.*;
- import org.dom4j.*;
- import org.dom4j.io.*;
- import org.dom4j.dom.*;
- public class Xml
- {
- protected Document document;
- protected Element root;
- protected int levelCounter = 0;
- protected StringBuilder xmlAsText = new StringBuilder();
- public Xml ( File f ) throws DocumentException
- {
- try
- {
- SAXReader reader = new SAXReader();
- document = reader.read( f );
- }
- catch ( DocumentException e )
- {
- e.printStackTrace();
- }
- init();
- }
- public Xml ( String fname ) throws DocumentException
- {
- this( new File( fname ) );
- }
- private void init ()
- {
- root = document.getRootElement();
- }
- public void write ( String fname ) throws Exception
- {
- try
- {
- FileOutputStream newFile = new FileOutputStream( fname );
- XMLWriter writer = new XMLWriter( newFile, OutputFormat.createPrettyPrint() );
- //document = ( Document) ( ( DOMDocument) document ).setXmlStandalone(true);
- writer.write( document );
- }
- catch ( Exception e )
- {
- e.printStackTrace();
- }
- }
- /* Fast looping
- [ https://dom4j.github.io/#looping ]
- */
- public void treeWalk()
- {
- treeWalk( document );
- }
- public void treeWalk( Document document )
- {
- treeWalk( document.getRootElement() );
- }
- public void treeWalk( Element element )
- {
- if ( levelCounter == 0 )
- {
- xmlAsText.append( "[" + levelCounter + "] " + element.getName() + " " + element.attributes().size() + "\n" );
- }
- levelCounter++;
- String previousParent = "";
- String indent=" ";
- for (int i = 0; i < element.nodeCount(); i++)
- {
- Node node = element.node( i );
- if (node instanceof Element)
- {
- previousParent = node.getParent().getName();
- treeWalk( (Element) node );
- }
- else
- { //if ( node.getText() != null && ! node.getText().equals("") )
- //if ( ! node.getText().trim().equals("") )
- if ( previousParent != element.getName() )
- {
- xmlAsText.append( indent.repeat(levelCounter) +
- "[" + levelCounter + "] " +
- element.getName() +
- ( ! node.getText().trim().equals("") ? " '" + node.getText().trim() + "'" : "" ) + "\n"
- );
- for (int j = 0; j < element.attributes().size(); j++)
- {
- Attribute a = element.attribute(j);
- xmlAsText.append( indent.repeat(levelCounter) +
- "[" + levelCounter + "] {" +
- a.getName() + " '" +
- a.getValue() + "'} " + "\n"
- );
- }
- }
- }
- }
- levelCounter--;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement