danmichaelo/quitesimplexmlelement

为SimpleXML添加了更易用的命名空间处理和一些辅助方法的外壳。

v1.0.2 2018-07-29 15:21 UTC

This package is auto-updated.

Last update: 2024-09-10 10:41:58 UTC


README

Build Status Coverage Status Code Quality SensioLabsInsight Latest Stable Version Total Downloads

QuiteSimpleXMLElement 类是围绕 SimpleXMLElement 类构建的一个小型外壳,增加了便利的方法并使得处理命名空间更加容易。开发此类的主要原因是让 xpath() 方法返回的对象能够从原始对象继承命名空间。该软件包之前被称为 CustomXMLElement

QuiteSimpleXMLElement 支持 PHP 5.6 和 7.x。如果您需要 PHP 5.3 支持,请使用 0.4.* 版本范围,因为 PHP 5.3 支持已在 0.5 版本中移除。

该库正在积极维护,欢迎提交拉取请求。

为什么开发这个库

以一个示例文档为例,

$xml = '<root xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:a>
      <dc:b >
        1.9
      </dc:a>
    </dc:b>
  </root>';

使用 SimpleXMLElement,我发现自己不得不反复注册命名空间

$root = new SimpleXMLElement($xml);
$root->registerXPathNamespace('d', 'http://purl.org/dc/elements/1.1/');
$a = $root->xpath('d:a');
$a[0]->registerXPathNamespace('d', 'http://purl.org/dc/elements/1.1/');
$b = $a[0]->xpath('d:b');

当使用 QuiteSimpleXMLElement 时,只需注册一次命名空间即可。

$node = new QuiteSimpleXMLElement($xml);
$node->registerXPathNamespace('d', 'http://purl.org/dc/elements/1.1/');
$a = $node->xpath('d:a');
$b = $a->xpath('d:b');

命名空间还可以使用替代构造函数 QuiteSimpleXMLElement::make 定义

$node = QuiteSimpleXMLElement::make($xml, ['d' => 'http://purl.org/dc/elements/1.1/']);
$a = $node->xpath('d:a');
$b = $a->xpath('d:b');

关于设计的说明:我原本希望扩展原始 SimpleXMLElement 类,但由于构造函数是静态的,所以我写了这个外壳。

辅助方法

该库定义了一些新方法以支持更少的键入和更干净的代码。

attr($name)

以字符串形式返回属性的值。支持命名空间前缀。

echo $node->attr('id');

text($xpath)

返回节点的文本内容

echo $node->text('d:a/d:b');

first($xpath)

返回匹配给定路径的第一个节点,如果没有则返回 null。

$node = $node->first('d:a/d:b');

all($xpath)

返回匹配给定路径的所有节点,如果没有则返回空数组。

$node = $node->all('d:a/d:b');

has($xpath)

如果节点存在则返回 true,否则返回 false。

if ($node->has('d:a/d:b') {
	…
}

setValue($value)

设置节点的值

$node->setValue('Hello world');

replace($newNode)

用新节点替换当前节点。示例

$book = new QuiteSimpleXMLElement('
<book>
	<chapter>
		<title>Chapter one</title>
	</chapter>
	<chapter>
		<title>Chapter two</title>
	</chapter>
</book>
');

$introduction = new QuiteSimpleXMLElement('
	<introduction>
		<title>Introduction</title>
	</introduction>
');

$firstChapter = $book->first('chapter');
$firstChapter->replace($introduction);

给出

<?xml version="1.0"?>
<book>
    <introduction>
        <title>Introduction</title>
    </introduction>
    <chapter>
        <title>Chapter two</title>
    </chapter>
</book>

同样支持命名空间,但替换节点中使用的任何命名空间都必须在该文档中指定。请参阅 QuiteSimpleXMLElementTest.php 以获取示例。