XmlUtilities

XmlUtilities:

Diese Klasse beinhaltet XmlUtilities

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
package de.soderer.utilities.xml;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * Utilities class to work with XML documents.
 */

public class XmlUtilities {
  /** Logger. */
  private static final transient Logger logger = Logger.getLogger(XmlUtilities.class);

  /**
   * Gets the empty document.
   *
   * @return the empty document
   * @throws ParserConfigurationException the parser configuration exception
   */

  public static Document getEmptyDocument() throws ParserConfigurationException {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    return document;
  }
  
  /**
   * Download and parse xml file.
   *
   * @param url the url
   * @return the document
   * @throws IOException the IO exception
   */

  public static Document downloadAndParseXmlFile(String url) throws IOException {
    BufferedInputStream inputStream = null;
    try {
      inputStream = new BufferedInputStream(new URL(url).openStream());
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
      Document document = documentBuilder.parse(new InputSource(inputStream));
      return document;
    } catch (Exception e) {
      return null;
    } finally {
      if (inputStream != null) {
        inputStream.close();
      }
    }
  }

  /**
   * Gets a single x path node.
   *
   * @param document the document
   * @param xpathExpression the xpath expression
   * @return the single x path node
   */

  public static Node getSingleXPathNode(Document document, String xpathExpression) {
    if (document == null) {
      return null;
    } else if (StringUtils.isBlank(xpathExpression)) {
      return null;
    } else {
      try {
        NodeList nodeList = (NodeList)XPathFactory.newInstance().newXPath().evaluate(xpathExpression, document, XPathConstants.NODESET);
        if (nodeList != null && nodeList.getLength() > 0) {
          return nodeList.item(0);
        } else {
          return null;
        }
      } catch (XPathExpressionException e) {
        return null;
      }
    }
  }
  
  /**
   * Parses a xml string.
   *
   * @param xmlInput the xml input
   * @return the document
   * @throws Exception the exception
   */

  public static Document parseXmlString(String xmlInput) throws Exception {
    boolean validation = false;
    boolean ignoreWhitespace = true;
    boolean ignoreComments = true;
    boolean putCDATAIntoText = true;
    boolean createEntityRefs = false;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    // set the configuration options
    dbf.setValidating(validation);
    dbf.setIgnoringComments(ignoreComments);
    dbf.setIgnoringElementContentWhitespace(ignoreWhitespace);
    dbf.setCoalescing(putCDATAIntoText);
    // The opposite of creating entity ref nodes is expanding them inline
    dbf.setExpandEntityReferences(!createEntityRefs);

    DocumentBuilder db = null;
    Document doc = null;
    try {
      db = dbf.newDocumentBuilder();
      doc = db.parse(new InputSource(new StringReader(xmlInput)));
      return doc;

    } catch (Exception e) {
      logger.error("Error while parsing xml", e);
      throw e;
    }
  }

  /**
   * Ignores DTD for better performance. This works faster for XHTML, because it doesn't download the dtd from any website like "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
   *
   * @param xmlInput the xml input
   * @return the document
   * @throws Exception the exception
   */

  public static Document parseXmlStringIngoringDtd(String xmlInput) throws Exception {
    if (xmlInput == null) {
      throw new Exception("XML-Data is null");
    } else if (StringUtils.isBlank(xmlInput)) {
      throw new Exception("XML-Data is empty");
    }

    boolean validation = false;
    boolean ignoreWhitespace = true;
    boolean ignoreComments = true;
    boolean putCDATAIntoText = true;
    boolean createEntityRefs = false;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    // set the configuration options
    dbf.setValidating(validation);
    dbf.setIgnoringComments(ignoreComments);
    dbf.setIgnoringElementContentWhitespace(ignoreWhitespace);
    dbf.setCoalescing(putCDATAIntoText);
    // The opposite of creating entity ref nodes is expanding them inline
    dbf.setExpandEntityReferences(!createEntityRefs);

    DocumentBuilder db = null;
    Document doc = null;
    try {
      db = dbf.newDocumentBuilder();

      db.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
          return new InputSource(new StringReader(""));
        }
      });

      doc = db.parse(new InputSource(new StringReader(xmlInput)));
      return doc;
    } catch (Exception e) {
      logger.error("Error while parsing xHtml", e);
      throw e;
    }
  }

  /**
   * Returns the content of a simple text tag If there are more than one text node or other nodetypes it will return null.
   *
   * @param node the node
   * @return the simple text value from node
   */

  public static String getSimpleTextValueFromNode(Node node) {
    if (node != null && node.getChildNodes().getLength() == 1 && node.getChildNodes().item(0).getNodeType() == Node.TEXT_NODE) {
      return node.getChildNodes().item(0).getTextContent();
    } else {
      return null;
    }
  }

  /**
   * Gets a attribute value.
   *
   * @param pNode the p node
   * @param pAttributeName the p attribute name
   * @return the attribute value
   */

  public static String getAttributeValue(Node pNode, String pAttributeName) {
    String returnString = null;

    NamedNodeMap attributes = pNode.getAttributes();
    if (attributes != null) {
      for (int i = 0; i < attributes.getLength(); i++) {
        if (attributes.item(i).getNodeName().equalsIgnoreCase(pAttributeName)) {
          returnString = attributes.item(i).getNodeValue();
          break;
        }
      }
    }

    return returnString;
  }

  /**
   * Gets a node value.
   *
   * @param pNode the p node
   * @return the node value
   */

  public static String getNodeValue(Node pNode) {
    if (pNode.getNodeValue() != null) {
      return pNode.getNodeValue();
    } else if (pNode.getFirstChild() != null) {
      return getNodeValue(pNode.getFirstChild());
    } else {
      return null;
    }
  }

  /**
   * Gets the node as string.
   *
   * @param pNode the p node
   * @param encoding the encoding
   * @param pRemoveXmlLine the p remove xml line
   * @return the node as string
   * @throws Exception the exception
   */

  public static String getNodeAsString(Node pNode, String encoding, boolean pRemoveXmlLine) throws Exception {
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    transformNode(pNode, encoding, pRemoveXmlLine, result);
    return writer.toString();
  }

  /**
   * Gets the node as raw.
   *
   * @param pNode the p node
   * @param encoding the encoding
   * @param pRemoveXmlLine the p remove xml line
   * @return the node as raw
   * @throws Exception the exception
   */

  public static byte[] getNodeAsRaw(Node pNode, String encoding, boolean pRemoveXmlLine) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(outputStream);
    transformNode(pNode, encoding, pRemoveXmlLine, result);
    return outputStream.toByteArray();
  }

  /**
   * Write document to file.
   *
   * @param document the document
   * @param encoding the encoding
   * @param file the file
   * @throws Exception the exception
   */

  public static void writeDocumentToFile(Document document, String encoding, File file) throws Exception {
    OutputStream outputStream = null;
    try {
      outputStream = new FileOutputStream(file);
      StreamResult result = new StreamResult(outputStream);
      transformNode(document, encoding, false, result);
    } finally {
      IOUtils.closeQuietly(outputStream);
    }
  }

  /**
   * Transform node.
   *
   * @param node the node
   * @param encoding the encoding
   * @param removeXmlHeader the remove xml header
   * @param result the result
   * @throws Exception the exception
   */

  private static void transformNode(Node node, String encoding, boolean removeXmlHeader, StreamResult result) throws Exception {
    TransformerFactory transformerFactory = null;
    Transformer transformer = null;
    DOMSource source = null;

    try {
      transformerFactory = TransformerFactory.newInstance();
      if (transformerFactory == null) {
        throw new Exception("TransformerFactory error");
      }

      transformer = transformerFactory.newTransformer();
      if (transformer == null) {
        throw new Exception("Transformer error");
      }

      transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
      if (removeXmlHeader) {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      } else {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      }

      source = new DOMSource(node);

      transformer.transform(source, result);
    } catch (TransformerFactoryConfigurationError e) {
      throw new Exception("TransformerFactoryConfigurationError", e);
    } catch (TransformerConfigurationException e) {
      throw new Exception("TransformerConfigurationException", e);
    } catch (TransformerException e) {
      throw new Exception("TransformerException", e);
    }
  }

  /**
   * Parses the xml data and xsd verify by dom.
   *
   * @param pData the p data
   * @param byteEncoding the byte encoding
   * @param xsdFileName the xsd file name
   * @return the document
   * @throws Exception the exception
   * @throws Exception the exception
   */

  public static Document parseXMLDataAndXSDVerifyByDOM(byte[] pData, String byteEncoding, String xsdFileName) throws Exception, Exception {
    try {
      if (pData == null) {
        return null;
      }

      if (pData[pData.length - 1] == 0) {
        pData = new String(pData, "UTF-8").trim().getBytes("UTF-8");
      }

      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
      if (docBuilderFactory == null) {
        throw new Exception("DocumentBuilderFactory error");
      }
      docBuilderFactory.setNamespaceAware(true);

      if (xsdFileName != null) {
        String schemaURI = xsdFileName;
        docBuilderFactory.setValidating(true);
        docBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
        docBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaURI);
      }

      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
      if (docBuilder == null) {
        throw new Exception("DocumentBuilder error");
      }

      InputSource inputSource = new InputSource(new ByteArrayInputStream(pData));
      if (byteEncoding != null) {
        inputSource.setEncoding(byteEncoding);
      }
      ParseErrorHandler errorHandler = new ParseErrorHandler();
      docBuilder.setErrorHandler(errorHandler);

      Document xmlDocument = docBuilder.parse(inputSource);

      if (errorHandler.problemsOccurred()) {
        throw new Exception("ErrorConstGlobals.XML_SCHEMA_ERROR " + xsdFileName + " " + errorHandler.getMessage());
      } else {
        return xmlDocument;
      }
    } catch (ParserConfigurationException e) {
      logger.error(e.getClass().getSimpleName(), e);
      throw new Exception("ErrorConstException.XML_PROCESSING " + e.getClass().getSimpleName() + " " + e.getMessage(), e);
    } catch (SAXException e) {
      logger.error(e.getClass().getSimpleName(), e);
      throw new Exception("ErrorConstException.XML_PROCESSING " + e.getClass().getSimpleName() + " " + e.getMessage(), e);
    } catch (IOException e) {
      logger.error(e.getClass().getSimpleName() + " während der XML-Verarbeitung", e);
      throw new Exception("ErrorConstException.XML_PROCESSING " + e.getClass().getSimpleName() + " " + e.getMessage(), e);
    }
  }

  /**
   * The Class ParseErrorHandler.
   */

  private static class ParseErrorHandler implements ErrorHandler {
    
    /** The warnings. */
    ArrayList<SAXParseException> warnings = null;
    
    /** The errors. */
    ArrayList<SAXParseException> errors = null;
    
    /** The fatal errors. */
    ArrayList<SAXParseException> fatalErrors = null;

    /** The problems. */
    boolean problems = false;

    /**
     * Problems occurred.
     *
     * @return true, if problems occurred
     */

    public boolean problemsOccurred() {
      return problems;
    }

    /* (non-Javadoc)
     * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException)
     */

    public void warning(SAXParseException exception) throws SAXException {
      problems = true;
      if (warnings == null) {
        warnings = new ArrayList<SAXParseException>();
      }
      warnings.add(exception);
    }

    /* (non-Javadoc)
     * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException)
     */

    public void error(SAXParseException exception) throws SAXException {
      problems = true;
      if (errors == null) {
        errors = new ArrayList<SAXParseException>();
      }
      errors.add(exception);
    }

    /* (non-Javadoc)
     * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException)
     */

    public void fatalError(SAXParseException exception) throws SAXException {
      problems = true;
      if (fatalErrors == null) {
        fatalErrors = new ArrayList<SAXParseException>();
      }
      fatalErrors.add(exception);
    }

    /**
     * Gets the message.
     *
     * @return the message
     */

    public String getMessage() {
      if (fatalErrors != null && fatalErrors.size() > 0) {
        return fatalErrors.get(0).getMessage();
      } else if (errors != null && errors.size() > 0) {
        return errors.get(0).getMessage();
      } else if (warnings != null && warnings.size() > 0) {
        return warnings.get(0).getMessage();
      } else {
        return "No ParserErrors occured";
      }
    }
  }

  /**
   * Convert xml to string.
   *
   * @param pDocument the p document
   * @param encoding the encoding
   * @return the string
   * @throws Exception the exception
   */

  public static String convertXML2String(Document pDocument, String encoding) throws Exception {
    TransformerFactory transformerFactory = null;
    Transformer transformer = null;
    DOMSource domSource = null;
    StringWriter writer = new java.io.StringWriter();
    StreamResult result = null;

    try {
      transformerFactory = TransformerFactory.newInstance();
      if (transformerFactory == null) {
        throw new Exception("TransformerFactory error");
      }

      transformer = transformerFactory.newTransformer();
      if (transformer == null) {
        throw new Exception("Transformer error");
      }

      if (encoding != null) {
        transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
      } else {
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      }

      domSource = new DOMSource(pDocument);
      result = new StreamResult(writer);

      transformer.transform(domSource, result);

      return writer.toString();
    } catch (TransformerFactoryConfigurationError e) {
      throw new Exception("TransformerFactoryConfigurationError", e);
    } catch (TransformerConfigurationException e) {
      throw new Exception("TransformerConfigurationException", e);
    } catch (TransformerException e) {
      throw new Exception("TransformerException", e);
    } finally {
      try {
        if (writer != null) {
          writer.close();
        }
      } catch (IOException ex) {
        throw new Exception("IO error", ex);
      }
    }
  }

  /**
   * Convert xml to byte array.
   *
   * @param pDocument the p document
   * @param encoding the encoding
   * @return the byte[]
   * @throws Exception the exception
   */

  public static byte[] convertXML2ByteArray(Node pDocument, String encoding) throws Exception {
    TransformerFactory transformerFactory = null;
    Transformer transformer = null;
    DOMSource domSource = null;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    StreamResult result = null;

    try {
      transformerFactory = TransformerFactory.newInstance();
      if (transformerFactory == null) {
        throw new Exception("TransformerFactory error");
      }

      transformer = transformerFactory.newTransformer();
      if (transformer == null) {
        throw new Exception("Transformer error");
      }

      if (encoding != null) {
        transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
      } else {
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      }

      domSource = new DOMSource(pDocument);
      result = new StreamResult(outputStream);

      transformer.transform(domSource, result);

      return outputStream.toByteArray();
    } catch (TransformerFactoryConfigurationError e) {
      throw new Exception("TransformerFactoryConfigurationError", e);
    } catch (TransformerConfigurationException e) {
      throw new Exception("TransformerConfigurationException", e);
    } catch (TransformerException e) {
      throw new Exception("TransformerException", e);
    } finally {
      try {
        if (outputStream != null) {
          outputStream.close();
        }
      } catch (IOException ex) {
        throw new Exception("IO error", ex);
      }
    }
  }

  /**
   * Creates the root tag node.
   *
   * @param baseDocument the base document
   * @param rootTagName the root tag name
   * @return the element
   */

  public static Element createRootTagNode(Document baseDocument, String rootTagName) {
    Element newNode = baseDocument.createElement(rootTagName);
    baseDocument.appendChild(newNode);
    return newNode;
  }

  /**
   * Append node.
   *
   * @param baseNode the base node
   * @param tagName the tag name
   * @return the element
   */

  public static Element appendNode(Node baseNode, String tagName) {
    Element newNode = baseNode.getOwnerDocument().createElement(tagName);
    baseNode.appendChild(newNode);
    return newNode;
  }

  /**
   * Append text value node.
   *
   * @param baseNode the base node
   * @param tagName the tag name
   * @param tagValue the tag value
   * @return the element
   */

  public static Element appendTextValueNode(Node baseNode, String tagName, int tagValue) {
    return appendTextValueNode(baseNode, tagName, Integer.toString(tagValue));
  }

  /**
   * Append text value node.
   *
   * @param baseNode the base node
   * @param tagName the tag name
   * @param tagValue the tag value
   * @return the element
   */

  public static Element appendTextValueNode(Node baseNode, String tagName, String tagValue) {
    Element newNode = appendNode(baseNode, tagName);
    if (tagValue == null) {
      newNode.appendChild(baseNode.getOwnerDocument().createTextNode("<null>"));
    } else {
      newNode.appendChild(baseNode.getOwnerDocument().createTextNode(tagValue));
    }
    return newNode;
  }

  /**
   * Append attribute.
   *
   * @param baseNode the base node
   * @param attributeName the attribute name
   * @param attributeValue the attribute value
   */

  public static void appendAttribute(Element baseNode, String attributeName, boolean attributeValue) {
    appendAttribute(baseNode, attributeName, attributeValue ? "true" : "false");
  }

  /**
   * Append attribute.
   *
   * @param baseNode the base node
   * @param attributeName the attribute name
   * @param attributeValue the attribute value
   */

  public static void appendAttribute(Element baseNode, String attributeName, int attributeValue) {
    appendAttribute(baseNode, attributeName, Integer.toString(attributeValue));
  }

  /**
   * Append attribute.
   *
   * @param baseNode the base node
   * @param attributeName the attribute name
   * @param attributeValue the attribute value
   */

  public static void appendAttribute(Element baseNode, String attributeName, String attributeValue) {
    Attr typeAttribute = baseNode.getOwnerDocument().createAttribute(attributeName);
    if (attributeValue == null) {
      typeAttribute.setNodeValue("<null>");
    } else {
      typeAttribute.setNodeValue(attributeValue);
    }
    baseNode.setAttributeNode(typeAttribute);
  }

  /**
   * Removes the attribute.
   *
   * @param baseNode the base node
   * @param attributeName the attribute name
   */

  public static void removeAttribute(Element baseNode, String attributeName) {
    baseNode.getAttributes().removeNamedItem(attributeName);
  }

  /**
   * Adds the comment to document.
   *
   * @param pDocument the p document
   * @param pComment the p comment
   * @return the document
   */

  public static Document addCommentToDocument(Document pDocument, String pComment) {
    pDocument.getFirstChild().appendChild(pDocument.createComment(pComment));
    return pDocument;
  }

  /**
   * Gets the encoding of xml byte array.
   *
   * @param xmlData the xml data
   * @return the encoding of xml byte array
   * @throws Exception the exception
   */

  public static String getEncodingOfXmlByteArray(byte[] xmlData) throws Exception {
    String encodingAttributeName = "ENCODING";
    try {
      String first50CharactersInUtf8UpperCase = new String(xmlData, "UTF-8").substring(0, 50).toUpperCase();
      if (first50CharactersInUtf8UpperCase.contains(encodingAttributeName)) {
        int encodingstart = first50CharactersInUtf8UpperCase.indexOf(encodingAttributeName) + encodingAttributeName.length();

        int contentStartEinfach = first50CharactersInUtf8UpperCase.indexOf("'", encodingstart);
        int contentStartDoppelt = first50CharactersInUtf8UpperCase.indexOf("\"", encodingstart);
        int contentStart = Math.min(contentStartEinfach, contentStartDoppelt);
        if (contentStartEinfach < 0) {
          contentStart = contentStartDoppelt;
        }
        if (contentStart < 0) {
          throw new Exception("XmlByteArray-Encoding nicht ermittelbar");
        }
        contentStart = contentStart + 1;

        int contentEndSingle = first50CharactersInUtf8UpperCase.indexOf("'", contentStart);
        int contentEndDouble = first50CharactersInUtf8UpperCase.indexOf("\"", contentStart);
        int contentEnd = Math.min(contentEndSingle, contentEndDouble);
        if (contentEndSingle < 0) {
          contentEnd = contentEndDouble;
        }
        if (contentEnd < 0) {
          throw new Exception("XmlByteArray-Encoding nicht ermittelbar");
        }

        String encodingString = first50CharactersInUtf8UpperCase.substring(contentStart, contentEnd);
        return encodingString;
      } else {
        throw new Exception("XmlByteArray-Encoding nicht ermittelbar");
      }
    } catch (UnsupportedEncodingException e) {
      throw new Exception("XmlByteArray-Encoding nicht ermittelbar");
    }
  }
  
  /**
   * Returns all direct simple text value subnodes and their values for a dataNode
   *
   * Example XML:
   *   <dataNode>
   *     <a>1</a>
   *      <b>2</b>
   *      <c>3</c>
   *   </dataNode>
   * Returns: a=1, b=2, c=3.
   *
   * @param dataNode the data node
   * @return the simple values of node
   */

  public static Map<String, String> getSimpleValuesOfNode(Node dataNode) {
    Map<String, String> returnMap = new HashMap<String, String>();
    
    NodeList list = dataNode.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      Node node = list.item(i);
      if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.TEXT_NODE && node.getChildNodes().getLength() == 1) {
        returnMap.put(node.getNodeName(), node.getFirstChild().getNodeValue());
      }
    }
    
    return returnMap;
  }
  
  /**
   * Gets the sub nodes.
   *
   * @param dataNode the data node
   * @return the sub nodes
   */

  public static List<Node> getSubNodes(Node dataNode) {
    List<Node> returnList = new ArrayList<Node>();
    
    NodeList list = dataNode.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      Node node = list.item(i);
      returnList.add(node);
    }
    
    return returnList;
  }
  
  /**
   * Gets the nodenames of childs.
   *
   * @param dataNode the data node
   * @return the nodenames of childs
   */

  public static List<String> getNodenamesOfChilds(Node dataNode) {
    List<String> returnList = new ArrayList<String>();
    
    NodeList list = dataNode.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      Node node = list.item(i);
      if (node.getNodeType() != Node.TEXT_NODE) {
        returnList.add(node.getNodeName());
      }
    }
    
    return returnList;
  }
}