0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriot で XML の文字列をDOMする

0
Posted at
var xmlStr = '<root><hoge></hoge></root>';

// Parsing
var xmlDoc = null;
try {
    if (window.DOMParser) {
        xmlDoc = (new window.DOMParser()).parseFromString(xmlStr, "text/xml");
    } else {
        xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
    }
    if (!xmlDoc) {
        throw new Error('Unknown happening');
    }
} catch(e) {
    console.error("DOM にならん", e.message);
}
console.log(xmlDoc);


// Serializing
var strXml = null;
try {
    var xmlElement = xmlDoc.getElementsByTagName('hoge')[0];
    var attr = xmlDoc.createAttribute('name');
    attr.value = 'Kyoko Fukada';
    xmlElement.attributes.setNamedItem(attr);

    var xmlSerializer = new XMLSerializer();
    strXml = xmlSerializer.serializeToString(xmlDoc);
    if (!strXml) {
        throw new Error('Unknown case');
    }
} catch(e) {
    console.error("シリアライズできひん", e.message);
}
console.log(strXml);
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?