[go: up one dir, main page]

Menu

[r3]: / src / owagate / util / Xml.java  Maximize  Restore  History

Download this file

95 lines (79 with data), 3.0 kB

 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
/*-----------------------------------------------------------------------------
Xml.java
Copyright (C) 2007 Donald Griffin
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------------*/
package owagate.util;
import java.io.InputStream;
import java.util.regex.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.httpclient.HttpMethodBase;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
This class contains XML helper methods.
*/
public final class Xml
{
/**
Descends from the given parent looking for the first node to match path.
@param parent The DOM parent from which to start.
@param path The set of regular expressions for each level of the descent.
@return The child node at the end of the path or null if no match.
*/
public static Node getChild (Node parent, Pattern[] path)
{
Node c = parent;
int i;
for (i = 0; c != null && i < path.length; ++i)
for (c = c.getFirstChild(); c != null; c = c.getNextSibling())
{
String nn = c.getNodeName();
Matcher m = path[i].matcher(nn);
if (m != null && m.matches())
break;
}
return (i == path.length) ? c : null;
}
/**
Reads an XML Document from the given InputStream.
*/
public static Document readDocument (InputStream input)
{
try
{
DocumentBuilder builder = mDocFactory.newDocumentBuilder();
return builder.parse(input);
}
catch (Exception ex)
{
throw Ex.failed("Failed to read XML document", ex);
}
}
/**
Reads an XML Document from the given HttpMethodBase's response stream.
*/
public static Document readResponseDocument (HttpMethodBase method)
{
try
{
return readDocument(method.getResponseBodyAsStream());
}
catch (Exception ex)
{
throw Ex.failed("Failed to read XML document", ex);
}
}
private final static DocumentBuilderFactory mDocFactory = DocumentBuilderFactory.newInstance();
}