【问题标题】:adding prefix string all tag in xml php在xml php中添加前缀字符串所有标签
【发布时间】:2020-07-23 15:07:25
【问题描述】:

你好,我想像这样在我的 xml 标签上加上前缀

 <identifiant>
      <a:Nom>NOM</a:Nom>
      <a:NomJeuneFille i:nil="true" />
      <a:Prenom>PRENOM</a:Prenom>
</identifiant>

谁能帮帮我

【问题讨论】:

标签: php xml


【解决方案1】:

这是一个 XML 命名空间前缀,如果没有匹配的 XML 命名空间定义,它是无效的。 DOM 有特殊的方法来创建带有命名空间的 XML 节点:

// a list of namespaces just to avoid repeating the URIs
// the keys do not have to match the prefixes in the XML
$namespaces = [
  'xmlns' => 'http://www.w3.org/2000/xmlns/',
  'a' => 'urn:example:a',
  'i' => 'urn:example:i'
];

$document = new DOMDocument();
// the document element does not seem to have a namespace
$identifiant = $document->appendChild(
    $document->createElement('identifiant')
);
// add the namespace definition for prefix "a"
// namespace definition use a reserved, internal namespace
$identifiant->setAttributeNS($namespaces['xmlns'], 'xmlns:a', $namespaces['a']);

$identifiant->appendChild(
    // create an elment node with the namespace
    $document->createElementNS(
        $namespaces['a'],
        'a:Nom'
    )
)->textContent = 'NOM';

$identifiant
  ->appendChild(
    $document->createElementNS(
        $namespaces['a'],
        'a:NomJeuneFille'
    )
  )
  ->setAttributeNS(
        $namespaces['i'],
        'i:nil',
        'true'
  );


$identifiant->appendChild(
    $document->createElementNS(
        $namespaces['a'],
        'a:Prenom'
    )
)->textContent = 'PRENOM';

$document->formatOutput = TRUE;
echo $document->saveXML();

输出:

<?xml version="1.0"?>
<identifiant xmlns:a="urn:example:a">
  <a:Nom>NOM</a:Nom>
  <a:NomJeuneFille xmlns:i="urn:example:i" i:nil="true"/>
  <a:Prenom>PRENOM</a:Prenom>
</identifiant>

将根据需要添加命名空间定义。您可以通过在祖先节点上手动定义它来避免在兄弟分支上重复它。我为“a”前缀做了这个,“i”前缀的定义是自动添加的。

【讨论】:

  • 谢谢,但我的 XML 元素是从 json 生成的
  • 这不是反对 DOM 的理由。您正在读取一个数据源(不管是 JSON 还是数据库)并创建一个特定的 XML 输出。
【解决方案2】:

尝试查找并替换所选内容(大多数文本编辑器都允许您这样做)

如果您的文件看起来相似,您可以通过滥用以空格开头的想法来轻松替换开始的块

  • 找到 &lt;
  • 替换 &lt;a:

如果这还不够(即您有一个更复杂的文件或希望对大量文件执行此操作),您将需要使用 XML 解析器重排您的 XML 文档

程序看起来像

import XML parsing library
read XML file
iterate over the blocks of whatever depth until you find what you want
change the block names (perhaps copy to new blocks and switch 'em)
write the resulting file again (consider writing to a new file so you can compare them more easily)

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多