尝试使用java转换和迭代XML字符串时获取null

时间:2015-12-18 09:32:50

标签: java xml

尝试将XML对象转换为文档以迭代对象时,我得到null。请找到代码。

String XML_DATA = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
        "<list>" +
        "<string>abd5fd81-2bd6-4479-9d60-61fe533a13b7</string>" +
        "<string>e127393b-343b-433c-87fc-27289758cca8</string>" +
        "<string>753f79fe-a1d2-4383-b5c9-3ec8aa6b7e65</string>" +
        "<string>2c71f819-65a6-4b08-8870-e71b1c770992</string>" +
        "<string>ad22d8c0-8187-4243-8189-92e94c969208</string>" +
        "<string>e6e70ab9-6149-4dfd-9d88-e27ec419847e</string>" +
        "<string>87d8566b-4c8a-4ef0-9fa9-c7b8805e5631</string>" +
        "<string>1309a729-20b4-40bb-96c8-46c96f205e60</string>" +
        "<string>5e78b822-d472-4f02-859d-de36183c5d01</string>" +
        "<string>410c70fb-8b05-47ef-bfbf-29284e45c8d3</string>" +
        "</list>";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
System.out.println(builder.parse(new InputSource(new StringReader(XML_DATA))));//Displaying null
Document document = builder.parse(new InputSource(new StringReader(XML_DATA)));
System.out.println(document);

1 个答案:

答案 0 :(得分:0)

您的文档实际上不为空,System.out.println调用toString()的{​​{1}}方法,显示以下Document

String

无论如何,您不想对[#document: null] 对象的字符串表示做任何事情。

因此,只需调用感兴趣的方法并按照您的需要执行操作,例如获取与Document标记匹配的NodeList

list