我只想读取Dom对象中的特定节点“ MessageEvent”,其中doc是已经生成的Dom对象。有任何想法吗?谢谢。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = factory.newDocumentBuilder();
doc = dBuilder.parse(xmlFile);

doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("MessageEvent");


这是XML:

<MessageEvent>
<Message.Event.MaximumSeverity.Code>Information</Message.Event.MaximumSeverity.Code>
    <MessageEventItems>
        <MessageEventItem>
            <Message.Event.Item.Error.Code>OK</Message.Event.Item.Error.Code>
            <Message.Event.Item.Severity.Code>Information</Message.Event.Item.Severity.Code>
            <Message.Event.Item.Short.Description>sucessfully</Message.Event.Item.Short.Description>
        </MessageEventItem>
</MessageEventItems>

最佳答案

我已经测试过了:

<?xml version="1.0" encoding="UTF-8"?>
<MessageEvent>
   <Message.Event.MaximumSeverity.Code>Information</Message.Event.MaximumSeverity.Code>
   <MessageEventItems>
        <MessageEventItem>
            <Message.Event.Item.Error.Code>OK</Message.Event.Item.Error.Code>
            <Message.Event.Item.Severity.Code>Information</Message.Event.Item.Severity.Code>
            <Message.Event.Item.Short.Description>sucessfully</Message.Event.Item.Short.Description>
        </MessageEventItem>
    </MessageEventItems>
</MessageEvent>


我尝试通过代码:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = factory.newDocumentBuilder();
Document doc = dBuilder.parse("D:/test.xml");
doc.getDocumentElement().normalize();
Element element = doc.getDocumentElement();
System.out.println(element); // picks up the root element


我得到的输出是这样的:

[MessageEvent: null]


希望这对您有帮助。 :)

09-12 18:55