LoginSignup
0
0

More than 5 years have passed since last update.

document.createElementNS() で 出力する XML で タグに prefix が付かないメモ

Posted at

既存の XML を XMLParse して dom を作って

<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:item="http://...../item">
</rdf:Description>

という XML の Description に項目を足して

<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:item="http://...../item">
  <item:name>ほげ</item:name>
  <item:type>ほげほげ</item:type>
</rdf:Description>

という XML を出力したくて

const nsRdf  = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
const nsItem = "http://...../item";

var desc = dom.getElementsByTagNameNS(nsRdf, "Description");

let el = document.createElementNS(nsItem, "name");
el.textContent = "ほげ";
desc.appendChild(el);

el = document.createElementNS(nsItem, "type");
el.textContent = "ほげほげ";
desc.appendChild(el);

console.log(desc);

してみても

<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:item="http://...../item">
  <name>ほげ</name>
  <type>ほげほげ</type>
</rdf:Description>

という風に、足したタグに prefix item が付かない。

el.prefixel.namespaceURI を表示してみると

el: <name>ほげ</name>
prefix: null
nsURI: http://...../item

という結果。

結論

el = document.createElementNS(nsItem, "item:name");

と書けという事。

el: <item:name>ほげ</item:name>
prefix: item
nsURI: http://...../item

となりました。

getElementsByTagNameNS() では "rdf:Description" を検索してもヒットせず "Description" で検索するものだから、 namespace を指定したら prefix 外すと思い込んでいて・・・

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0