yuubit/paxb

公共库 PAXB - PHP 注解 XML 绑定,基于注解驱动的 XML 绑定的基本实现

维护者

详细信息

github.com/Yuubit/paxb

源代码

1.0.1-alpha2 2019-01-28 10:05 UTC

This package is auto-updated.

Last update: 2024-09-28 23:51:37 UTC


README

PAXB - 基于注解驱动的 XML 绑定的非常基本实现

支持的注解

此库支持以下列出的注解

  • XmlAttribute(name="")
  • XmlElement(name="", type="") - 对于包含对象的字段反序列化,type 是必需的
  • XmlElementWrapper(name) - 名称是必需的
  • XmlTransient
  • XmlValue

这些注解只能用作属性注解或类注解(XmlElement 仅限)

示例代码

序列化示例

    /**
     * @XmlElement(name="root")
     */
    class SampleEntity {

        /**
         * @XmlElement(name="attribute-value", type="AttributeValueEntity")
         */
        private $nestedEntity;

        private $text;

        /**
         * @XmlElementWrapper(name="number-list")
         */
        private $number = array();


        public function __construct($number = array(), $nestedEntity = null, $text = "")
        {
            $this->number = $number;
            $this->nestedEntity = $nestedEntity;
            $this->text = $text;
        }
    }

    class AttributeValueEntity {

        /**
         * @XmlAttribute
         */
        private $attribute;

        /**
         * @XmlElement
         */
        private $value;

        /**
         * @param string $attribute
         * @param string $value
         */
        public function __construct($attribute = "", $value = "")
        {
            $this->attribute = $attribute;
            $this->value = $value;
        }

        /**
         * @return string
         */
        public function getAttribute()
        {
            return $this->attribute;
        }

        /**
         * @return string
         */
        public function getValue()
        {
            return $this->value;
        }
    }

序列化代码

    $sampleEntity = new SampleEntity(
        array(1,2,3),
        new AttributeValueEntity('sample attribure', 'sample value'),
        'Sample text'
    );

    echo PAXB\Setup::getMarshaller()->marshall($sampleEntity, true);

输出

    <?xml version="1.0"?>
    <root>
        <attribute-value attribute="sample attribure">
            <value>sample value</value>
        </attribute-value>
        <text>Sample text</text>
        <number-list>
            <number>1</number>
            <number>2</number>
            <number>3</number>
        </number-list>
    </root>

反序列化示例

    $xmlInput = '...'; //as above
    /** @var SampleEntity $sampleEntity */
    $sampleEntity = PAXB\Setup::getUnmarshaller()->unmarshall($xmlInput, 'SampleEntity');

运行示例

  1. 安装 composer: php -r "eval('?>'.file_get_contents('https://getcomposer.org.cn/installer'));"
  2. 安装依赖:./composer.phar install
  3. 运行演示脚本:php demo/demo-marshall.php 或 php demo/demo-unmarshall.php