Nipper Studio XML 解析器

问题描述

<section index="2.3" title="No HTTP(S) Server Session Timeout or HTTP(S) Server Idle Timeout Set" ref="ADMINISTRATION.WEBTIMEOUT.NO.HTTP.OR.HTTPS.SESSION.OR.IDLE.TIMEOUT.four">
    <issuedetails>
        <devices>
            <device name="Switch" type="Cisco Catalyst Switch" osversion="16.3" />
        </devices>
        <ratings type="Nipperv1">
            <rating>High</rating>
            <impact>Critical</impact>
            <ease>Easy</ease>
            <fix>Quick</fix>
            <FindingID>NSA-ADMIN-046</FindingID>
            <classif>Administration</classif>
        </ratings>
    </issuedetails>
    <section index="2.3.1" title="Finding" ref="FINDING">
    </section>
    <section index="2.3.4" title="Recommendation" ref="RECOMMENDATION">
        <text>Nipper Studio recommends that a HTTP(S) server session timeout period of 10 minutes or less should be configured.</text>
        <text>Notes for Cisco Catalyst Switch devices:</text>
        <text>The HTTP server timeout can be configured with the following command:<code><command>ip http timeout-policy idle <cmduser>seconds</cmduser> life <cmduser>seconds</cmduser> requests <cmduser>number</cmduser></command>
        </code>
        </text>

XML 解析器:

$commands = $section->xpath('section[4]/text/code/command');
$object->commands = "";
foreach($commands as $command)
{
    $object->commands .=  $command;
    $cmdusers = $command->xpath('cmduser');
    foreach($cmdusers as $cmduser){
        $object->commands .=  $cmduser;
    }
    $object->commands .=  "<br>";
}
echo "commands : <br>".$object->commands;
echo "<be>";

输出

ip http timeout-policy idle seconds life seconds requests number

但事情是这样的

ip http timeout-policy idle life requests secondssecondsnumber

解决方法

在这种情况下,您可以只使用一个 XPath:

setValues()
,

您已经看到您的期望与实际结果不符。

这只是 SimpleXML 的一个限制,所以它有点属于“错误的工作工具”类别。但请继续阅读,它用途广泛。

是什么让您感到困难,因为您将 SimpleXML 解析器用于 XML 的结构不太适合它 - 至少在这个地方是这样。

有问题的部分是寻找跨越多个元素节点的文本数据。

Echoing the contents of an xml-file with nested tags 中的 an answer by cOle2 所述:

目前您的 $output 是一个 SimpleXMLElement,当您回显它时,会调用 internal toString() method。根据注释,此方法不会返回此元素子元素内的文本内容,这就是排除某些文本的原因。

在使用 SimpleXML 的同时获取 text-content 的一种方法是使用 DOM 姊妹库 which is similar to my answer to the other question,这是一个简单的导入操作,然后获取属性:

$commands = $section->xpath('section[4]/text/code/command');
$object->commands = "";
foreach($commands as $command)
{
    $object->commands .=  dom_import_simplexml($command)->textContent;
                                  ^^^^            ^^^         ^^^^
    ...

根据经验,SimpleXML 在 XML 文本节点方面很弱。它的 API 中没有任何具体内容,字符串值表示叶元素节点文本内容。其他元素节点字符串内容可能会出现不完整和顺序错误 - 就像您可能遇到的那样。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...