1.首先获取 xml文档
@Test
public void testXml() {
File file = new File("2.1.1.10值机柜台变更报文.xml");
String strMsg = new String(Utils.readXml(file));
Utils.parserXMl(strMsg);
}
2. 将 file 文件 转换成字节数组 作为字符串对象的参数 ,
@Test
public static byte[] readXml(File file) {
// File file = new File("2.1.1.10值机柜台变更报文.xml");
// 将file文件 转成 字节数组 ,
InputStream in = null;
byte[] buffer = null;
try {
buffer = new byte[(int) file.length()];
in = new FileInputStream(file);
DataInputStream din = new DataInputStream(in);
din.readFully(buffer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return buffer;
}
3. 将string 字符串 转换成 dom对象
// 解析 xml 字符串
public static void parserXMl(String msg) {
SAXReader sax = new SAXReader();
try {
Document doc = sax.read(new ByteArrayInputStream(msg.getBytes()));
List<Element> list = SelectNodeByDefaultNS(doc, "/AIIS/FLIGHTMOVEMENT/ACTIVEFLIGHT");
System.out.println(list.size());
Element element = list.get(0);
Node n = element;
System.out.println(element.elementText("FLIGHTID"));
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
4.通过xpath 获取节点的值
@SuppressWarnings("unchecked")
private static List<Element> SelectNodeByDefaultNS(Document doc, String path) {
// TODO Auto-generated method stub
String prefix = "default";
Namespace ns = doc.getRootElement().getNamespace();
Map<String,String> map = new HashMap<String,String>();
map.put(prefix, ns.getURI());
path = path.replaceAll("/", "/" + prefix + ":");
XPath xpath = doc.createXPath(path);
xpath.setNamespaceURIs(map);
return xpath.selectNodes(doc);
}
446

被折叠的 条评论
为什么被折叠?



