php - JMS序列化器读取xml :lang attribute

标签 php xml jms-serializer

这与 xml:lang parse in PHP 相关.

我们使用JMS serializer创建发送至 Sirena-Travel(机票提供商)的 XML 请求并解析来自 Sirena-Travel 的 XML 响应。整个带注释的 DTO 系统是围绕这个序列化器构建的,我们不太可能改变这一点。

我们想要反序列化一个响应 XML(与上面的问题相同):

<?xml version="1.0" encoding="UTF-8"?>
  <answer>
    <describe data="aircompany">
      <data>
        <code xml:lang="ru">FW</code>
        <code xml:lang="en">FW</code>
      </data>
      <data>
        <code xml:lang="ru">UT</code>
        <code xml:lang="en">ЮТ</code>
      </data>
    </describe>
  </answer>

问题是:如何指定与 xml:lang 属性对应的属性?

这就是描述最内部元素的类的样子:

class DescribeData
{
    /**
     * Codes in various languages.
     *
     * @Type("array<DescribeLangElement>")
     * @XmlList(inline = true, entry = "code")
     */
    private $codes = [];

    public function getCode($lang)
    {
        foreach ($this->codes as $code) {
            if ($code->getLang() === $lang) {
                return $code;
            }
        }
        return null;
    }
}

class DescribeLangElement
{
    /**
     * Element's language code.
     *
     * Either "en" or "ru".
     *
     * @Type("string")
     * @XmlAttribute
     */
    private $lang;

    /**
     * @Type("string")
     * @XmlValue
     */
    private $value;
}

显然,序列化程序无法将 xml:lang 属性识别为 $lang 属性。我尝试了几种方法:

  • @SerializedName("xml:lang") 添加到 $lang 属性。
  • 添加命名空间注释:

     @XmlNamespace(uri = "http://example.com/", prefix = "xml")
    

    无论是父节点还是根节点,同时修改 $lang 属性上的 @XmlAttribute 注释,使其看起来像这样

     @XmlAttribute(namespace = "http://example.com/")
    

不用说,其中一个或两个都没有成功。

我还想到了替代解决方案,例如:

  • 预处理 XML,将 xml:lang 属性转换为 lang
  • 编写自定义反序列化处理程序来处理 DescribeLangElement 类。

但这些对我来说似乎有点过分了。

是否有一种直接的方法可以使用 JMS 序列化器注释为 xml:lang 属性指定属性?

最佳答案

Namespace constraint: Reserved Prefixes and Namespace Names

The prefix xml is by definition bound to the namespace name http://www.w3.org/XML/1998/namespace. It may, but need not, be declared, and must not be undeclared or bound to any other namespace name. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace.

来自:http://www.w3.org/TR/xml-names11/#xmlReserved

因此命名空间不是 http://example.com/ 而是 http://www.w3.org/XML/1998/namespace

关于php - JMS序列化器读取xml :lang attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24389574/

相关文章:

php - 下载 xml 文件时,会在文件开头添加新行

java.lang.IllegalArgumentException : No view found for id 0x7f090047 ("project name":id/content) for fragment FmMenu 异常

android - 在 ImageView 中加载的图像隐藏了按钮

rest - 将自定义属性添加到序列化对象

php - Mysql/Php查询分组过滤结果

javascript - 如何在 Laravel 5.7 中将数据从一个表单传递到不同页面上的另一个表单?

java - 在 Web 收获 xml 中使用正则表达式

Symfony+JMS Serializer反序列化为现有对象

php - JMSSerializer 分组属性的交集

php - 虽然循环不显示所有值