GithubHelp home page GithubHelp logo

xmldom's Introduction

XMLDOM Build Status Coverage Status NPM version

A JavaScript implementation of W3C DOM for Node.js, Rhino and the browser. Fully compatible with W3C DOM level2; and some compatible with level3. Supports DOMParser and XMLSerializer interface such as in browser.

Install:

npm install xmldom

Example:

var DOMParser = require('xmldom').DOMParser;
var doc = new DOMParser().parseFromString(
    '<xml xmlns="a" xmlns:c="./lite">\n'+
        '\t<child>test</child>\n'+
        '\t<child></child>\n'+
        '\t<child/>\n'+
    '</xml>'
    ,'text/xml');
doc.documentElement.setAttribute('x','y');
doc.documentElement.setAttributeNS('./lite','c:x','y2');
var nsAttr = doc.documentElement.getAttributeNS('./lite','x')
console.info(nsAttr)
console.info(doc)

API Reference

  • DOMParser:

    parseFromString(xmlsource,mimeType)
    • options extension by xmldom(not BOM standard!!)
    //added the options argument
    new DOMParser(options)
    
    //errorHandler is supported
    new DOMParser({
    	/**
    	 * locator is always need for error position info
    	 */
    	locator:{},
    	/**
    	 * you can override the errorHandler for xml parser
    	 * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
    	 */
    	errorHandler:{warning:function(w){console.warn(w)},error:callback,fatalError:callback}
    	//only callback model
    	//errorHandler:function(level,msg){console.log(level,msg)}
    })
    	
  • XMLSerializer

    serializeToString(node)

DOM level2 method and attribute:

  • Node

     attribute:
     	nodeValue|prefix
     readonly attribute:
     	nodeName|nodeType|parentNode|childNodes|firstChild|lastChild|previousSibling|nextSibling|attributes|ownerDocument|namespaceURI|localName
     method:	
     	insertBefore(newChild, refChild)
     	replaceChild(newChild, oldChild)
     	removeChild(oldChild)
     	appendChild(newChild)
     	hasChildNodes()
     	cloneNode(deep)
     	normalize()
     	isSupported(feature, version)
     	hasAttributes()
    
  • DOMImplementation

     method:
     	hasFeature(feature, version)
     	createDocumentType(qualifiedName, publicId, systemId)
     	createDocument(namespaceURI, qualifiedName, doctype)
    
  • Document : Node

     readonly attribute:
     	doctype|implementation|documentElement
     method:
     	createElement(tagName)
     	createDocumentFragment()
     	createTextNode(data)
     	createComment(data)
     	createCDATASection(data)
     	createProcessingInstruction(target, data)
     	createAttribute(name)
     	createEntityReference(name)
     	getElementsByTagName(tagname)
     	importNode(importedNode, deep)
     	createElementNS(namespaceURI, qualifiedName)
     	createAttributeNS(namespaceURI, qualifiedName)
     	getElementsByTagNameNS(namespaceURI, localName)
     	getElementById(elementId)
    
  • DocumentFragment : Node

  • Element : Node

     readonly attribute:
     	tagName
     method:
     	getAttribute(name)
     	setAttribute(name, value)
     	removeAttribute(name)
     	getAttributeNode(name)
     	setAttributeNode(newAttr)
     	removeAttributeNode(oldAttr)
     	getElementsByTagName(name)
     	getAttributeNS(namespaceURI, localName)
     	setAttributeNS(namespaceURI, qualifiedName, value)
     	removeAttributeNS(namespaceURI, localName)
     	getAttributeNodeNS(namespaceURI, localName)
     	setAttributeNodeNS(newAttr)
     	getElementsByTagNameNS(namespaceURI, localName)
     	hasAttribute(name)
     	hasAttributeNS(namespaceURI, localName)
    
  • Attr : Node

     attribute:
     	value
     readonly attribute:
     	name|specified|ownerElement
    
  • NodeList

     readonly attribute:
     	length
     method:
     	item(index)
    
  • NamedNodeMap

     readonly attribute:
     	length
     method:
     	getNamedItem(name)
     	setNamedItem(arg)
     	removeNamedItem(name)
     	item(index)
     	getNamedItemNS(namespaceURI, localName)
     	setNamedItemNS(arg)
     	removeNamedItemNS(namespaceURI, localName)
    
  • CharacterData : Node

     method:
     	substringData(offset, count)
     	appendData(arg)
     	insertData(offset, arg)
     	deleteData(offset, count)
     	replaceData(offset, count, arg)
    
  • Text : CharacterData

     method:
     	splitText(offset)
    
  • CDATASection

  • Comment : CharacterData

  • DocumentType

     readonly attribute:
     	name|entities|notations|publicId|systemId|internalSubset
    
  • Notation : Node

     readonly attribute:
     	publicId|systemId
    
  • Entity : Node

     readonly attribute:
     	publicId|systemId|notationName
    
  • EntityReference : Node

  • ProcessingInstruction : Node

     attribute:
     	data
     readonly attribute:
     	target
    

DOM level 3 support:

  • Node

     attribute:
     	textContent
     method:
     	isDefaultNamespace(namespaceURI){
     	lookupNamespaceURI(prefix)
    

DOM extension by xmldom

  • [Node] Source position extension;

     attribute:
     	//Numbered starting from '1'
     	lineNumber
     	//Numbered starting from '1'
     	columnNumber
    

xmldom's People

Contributors

daurnimator avatar flatheadmill avatar frost avatar gierschv avatar heycam avatar isnotgood avatar jbeard4 avatar jindw avatar jinjinyun avatar kethinov avatar matt-deboer avatar microshine avatar nfischer avatar nightwing avatar olegas avatar shazron avatar skypanther avatar technosophos avatar yaronn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xmldom's Issues

`setAttributeNodeNS` should throw `INUSE_ATTRIBUTE_ERR`

Compare http://jsfiddle.net/cw5V8/ with the following program that emits no errors.

var xmldom = require('xmldom')
  , doc = new (xmldom.DOMParser)().parseFromString('<xml><a a=1 b=2 c=3/><a a=1 b=2 c=3/></xml>')
  , one = doc.documentElement.firstChild
  , two = one.nextSibling
  ;

one.setAttributeNodeNS(two.attributes.item(0));

console.log(one.toString(), two.toString());

Update: Fixed example code. I'd pasted twice.

XMLSerializer and namespaces?

Hi there.

Not entirely sure this is an issue, really, but does anyone know how to get the XMLSerializer to output namespace information?

Say, code like this:

var doc = new domi.createDocument( "http://www.example.org/", "hest:foo");

Gives this doc:

#2={doctype:(void 0), implementation:{}, childNodes:{0:#1={_nsMap:{}, attributes:{_ownerElement:#1#}, childNodes:{}, ownerDocument:#2#, nodeName:"hest:foo", tagName:"hest:foo", namespaceURI:"http://www.example.org/", prefix:"hest", localName:"foo", previousSibling:null, nextSibling:null, parentNode:#2#}, length:1}, documentElement:#1#, firstChild:#1#, lastChild:#1#, _inc:2}

But, toString() outputs:

"<hest:foo/>"

not what I would expect:

"<hest:foo xmlns:hest="http://www.example.org/" />"

Does anyone know is this is a bug, me using xmldom wrong, or?

Error handling

Here is example
This shows parsing absolutly invalid XML

    var parser = new DOMParser;
    var xmlDoc = parser.parseFromString("<t1><t2></t1></t2>");

    //serialize document
    var serializer = new XMLSerializer;
    var docText = serializer.serializeToString(xmlDoc);
    console.log("xml:",docText);        

No errors are reported. The reverse serialization provides:
"<t1><t2/></t1>"

Great! We autofixed all the errors in original XML without reporting a single problem. terminating t2 jumped inside t1 automagically.

Bug in DOMParser.parseFromString

When i try run these code:

var xmldom = require('xmldom');
var serializer = new (xmldom.XMLSerializer)();
var domParser = new (xmldom.DOMParser)();
var doc = domParser.parseFromString('<div><p><a></a><b></b></p></div>', 'text/html');

doc.toString() returns this

<div xmlns="http://www.w3.org/1999/xhtml"><p xmlns="http://www.w3.org/1999/xhtml"><a xmlns="http://www.w3.org/1999/xhtml"></a><b xmlns="http://www.w3.org/1999/xhtml"></b></p></div>

`jindw/xmldom` should pass the W3C DOM conformance test suites.

The W3C provides a conformance test suite. http://www.w3.org/DOM/Test/

There is a full Java implementation from which to crib. The tests themselves are specified in XML, so one would only have to write a Node.js interpreter to read through the tests and apply them.

I'd propose building a test harness that reads through the tests. Then, creating an issue for each failed test, or more likely, picking a test to tackle, creating an issue so there's an opportunity for discussion, then submitting a pull request.

setAttribute allows to set a non-string value. This is causing crash while serializing to string

node.setAttribute('myattr', 1); // OK

// later...
node.toString(); // ERROR!
// dom.js:948-949
// TypeError: Object 1 has no method 'replace'
// node.value is Number and has no replace method
case ATTRIBUTE_NODE:
    return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),

Maybe it is better to cast value to string while setting an attribute? If this is acceptable solution I can fix it and make a pull request.

parse msinfo32

I have this example

var fs = require('fs');
fs.readFile('C:\Temp\TEST.xml', 'ascii', function(err,data){
if(err) {
console.log("Could not open file"+ err);
process.exit(1);
}
var Dom = require('xmldom').DOMParser;
var doc = new Dom().parseFromString(data.substring(2,data.lenght));
console.log(doc.childNodes[0].localName);
});

output generated by "msinfo32 /nfo C:\TEMP\TEST.NFO"

After several minutes running it outputs this error:

\node_modules\xmldom\dom.js:337
normalize:function(){
^
RangeError: Maximum call stack size exceeded

Measure test coverage with Istanbul and report to coveralls.io.

  • Add istanbul and coveralls to installation section of .travis.yml.
  • Copy an existing copy of t/test.
  • Copy an existing copy of t/cover.
  • Add t/test invocation to package.json.
  • View local coverage report in browser.
  • Turn on project at coveralls.io.
  • Commit and push.
  • Add Coveralls chicklet.
  • Quiet all tests files.
  • Commit and push and close.

xmldom hangs and reports inaccurate XML on invalid XML

With this test case:

<Label onClick="doClick>Hello, World</Label>

if I attempt to use DOMParser.parseFromString(), the program will freeze and chew up all the CPU and memory on my computer. There's no error output, and it wil run until the machine runs out of memory.

With this test case:

<Label onClick=doClick">Hello, World</Label>

I would expect the XML parsing to abort here as it is invalid, but instead it returns this inaccurate string when serialized:

<Label onClick="doClick&quot;">Hello, World</Label>

Notice that I'm just moving the position of the missing double quote each time. So there's a number of weird things going on when xmldom encounters invalid XML. This is the test code I'm using to exhibit the previous problems:

var DOMParser = require("xmldom").DOMParser;
var XMLSerializer = require("xmldom").XMLSerializer;

// var test = '<Label onClick="doClick>Hello, World</Label>';
var test = '<Label onClick=doClick">Hello, World</Label>';

var xml = (new DOMParser()).parseFromString(test);
console.log((new XMLSerializer()).serializeToString(xml));

getElementsByTagNameNS doesn't work

Hi,

I have a problem with getElementsByTagNameNS, it doesn't seem to work with this example: I want to get the tagname <wp:docPr id="1" name="Image 1"/>

<?xml version="1.0" ?>
<w:document mc:Ignorable="w14 wp14" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape">
     <w:drawing>
          <wp:inline distT="0" distB="0" distL="0" distR="0">
               <wp:extent cx="2371148" cy="1999323"/>
               <wp:effectExtent l="0" t="0" r="0" b="0"/>
               <wp:docPr id="1" name="Image 1"/>
               <wp:cNvGraphicFramePr>
                    <a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/>
               </wp:cNvGraphicFramePr>
               <a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
                    <a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
                    <pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
                    <pic:nvPicPr>
                    <pic:cNvPr id="0" name="Image2.png"/>
               <pic:cNvPicPr/>
          </pic:nvPicPr>
               <pic:blipFill>
                    <a:blip r:embed="rId9">
                    <a:extLst>
                    <a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}">
                    <a14:useLocalDpi xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" val="0"/>
          </a:ext>
          </a:extLst>
          </a:blip>
               <a:stretch>
                    <a:fillRect/>
          </a:stretch>
          </pic:blipFill>
               <pic:spPr>
                    <a:xfrm>
                    <a:off x="0" y="0"/>
               <a:ext cx="2371148" cy="1999323"/>
          </a:xfrm>
               <a:prstGeom prst="rect">
                    <a:avLst/>
          </a:prstGeom>
          </pic:spPr>
          </pic:pic>
          </a:graphicData>
          </a:graphic>
          </wp:inline>
     </w:drawing>
</w:document>

In JS on chrome and Firefox, tag= xmlImg.getElementsByTagNameNS('*','docPr')[0] works, but it doesnt' on xmldom. Do you have an idea why, and how to fix it ?

parseFromString throws error when given plain text to parse

This example code throws the following error: source code out of document root

var xmldom = require('xmldom'),
    DOMParser = xmldom.DOMParser,
    XMLSerializer = new xmldom.XMLSerializer(),
    string = 'plain text',
    doc = new DOMParser().parseFromString(string, 'text/html'),
    s = XMLSerializer,
    str = s.serializeToString(doc);
console.log(str);

The resulting document given is this:

{ doctype: null,
  implementation: { _features: {} },
  childNodes: {},
  documentURI: undefined }

It should return a single textNode childNode instead of an empty set of childNodes.

I'll submit a pull request if I can figure out how to get it to do this, but as of yet I'm stumped after spending a few hours wading through the code.

Serialize fails to account for text node updates

Assuming D is a parsed-in XML DOM.
Assume further some text nodes in D are modified using
D.getElementsByTagName(...)[0].childNodes[0].nodeValue = ...;

Serializing D produces the original (unmodified parsed-in DOM)!
However, explicit reference to the modified nodes produces the expected (modified) values!

Issue demo code...

var winston = require('winston'); //multi-transport logger

var logger = new (winston.Logger) ({
transports: [
new winston.transports.Console({colorize: true})
]
});

var DOMParser = require('xmldom').DOMParser;

var XMLSerializer = require('xmldom').XMLSerializer;

var D = new DOMParser().parseFromString('dummy');

logger.info('Original element value= ' + D.getElementsByTagName('el')[0].childNodes[0].nodeValue);
D.getElementsByTagName('el')[0].childNodes[0].nodeValue = 'updated';
logger.info('Updated element value= ' + D.getElementsByTagName('el')[0].childNodes[0].nodeValue);

logger.info('Serialized updated D = ' + new XMLSerializer().serializeToString(D));

Throws type error when trying to parseFromString pages on https://www.npmjs.org

Irony alert: to replicate, call parseFromString on the html at https://www.npmjs.org/package/xmldom

Here's the output from parsing that page:
unclosed xml attribute
@#[line:2,col:1]
unclosed xml attribute
@#[line:3,col:1]
unclosed xml attribute
@#[line:4,col:3]
unclosed xml attribute
@#[line:6,col:3]
unclosed xml attribute
@#[line:7,col:3]
unclosed xml attribute
@#[line:8,col:3]
unclosed xml attribute
@#[line:9,col:3]
unclosed xml attribute
@#[line:10,col:3]
unclosed xml attribute
@#[line:12,col:1]
unclosed xml attribute
@#[line:51,col:7]
element parse error: Error: attribute invalid close char('/')
@#[line:51,col:98]
end tag name: a is not match the current start tagName:div
@#[line:51,col:99]
end tag name: a is not match the current start tagName:div
[TypeError: Cannot read property 'nodeType' of undefined]

No error raised with unclosed XML elements

No error is raised when container elements are unclosed. In our DOM, the <ImageView> element cannot contain children but must be closed (similar to <img> in HTML).

Given this XML:

<Alloy>
    <ImageView image="somefile.png"></ImageView> <!-- valid -->
    <ImageView image="somefile.png"/> <!-- valid -->
    <ImageView image="somefile.png"> <!-- unclosed, invalid -->
    ... 
</Alloy>

no error is raised with the third element when it should. It appears there's no way to specify that one should be raised (via option to new DOMParser()).

Agree upon a code formatting style.

The current code base as a code formatting style that I can follow for the most part, but I'm confused as to the preferences for indentation. Is it tabs or spaces? I see a mixture of tabs and spaces. I could easily adopt one or the other, but I'm not sure how to do both.

Thoughts?

cdata fix

hi

I've found a bug & solution for a cdata issue. the library was not able to parse cdata even in a simple case like:

the "x" node had no childs.

the problem is in sax.js in parseDCC (line 201).

instead of this:

appendText(reader,source.substring(9,end),0,end-9);

needs to be this:

appendText(reader,source.substring(9,end), end-9);

(the method only gets 3 parameters not 4).

is there any chance you can put it in the official branch and publish to npm?

thanks,
yaron

Regex issue after using UglifyJS

When trying to use XMLdom in a project that uses UglifyJS to minify it's source.
It breaks in Chrome on the line:

var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF

in sax.js, saying:

Uncaught SyntaxError: Invalid regular expression: /[A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-��-�Ⰰ-⿯�-퟿豈-�ﷰ-�]/: Range out of order in character class 

"Exports" Node & Element objects from "doc.js"

If "doc.js" exports these two objects, it would enable libs that depend on xmldom to extend these objects with useful functionalities that are used internally by the libs.

Thanks in advance

Parsing and iOS plist file

Hi there,

I am attempting to use xmldom to parse an iOS plist file that I plan to use for localization purposes in my javascript app. My end result will concatenate key / value tuples from multiple source (plist) files so that I have one master language file for my javascript app. Here is an example of how these source plist files are formatted:

CancelTitle
Cancel
EmailLabel
Email

To do so, I am trying to build a grunt task that will read the source file(s) and interpret it(them) as xml. In my Gruntfile.js, I have this under the grunt.initConfig block:

    translator: {
        options: {
          sourceFile: 'app/config/translations/original.plist'
        }
    }

Down below I register a task with this code:

grunt.registerTask('translate', [
    'translator'
]);

Inside of of the task directory file, I have this code:

module.exports = function (grunt) {

var xmldom = require('xmldom'),
    xpath = require('xpath'),
    _ = require('lodash'),
    ATTRIBUTE_NODE = 2;


grunt.registerMultiTask('translator', 'Updates values in XML files based on XPath queries', function () {

    var options = this.options();
    var sourceFile = options.sourceFile;
    var src =  grunt.file.read(sourceFile);
    var domParser = new xmldom.DOMParser();
    var doc = domParser.parseFromString(
            src
            ,'text/xml');
    var dictNode = xmlContent.getElementsByTagName('dict')[0];
    console.log(dictNode);
    ...

I am in the beginning stages of this project now and I am just trying to read the source file and interpret it as xml. After running grunt translate, I am receiving this error in the console:

end tag name: string is not match the current start tagName:dict
@#[line:3225,col:43]

Nothing comes up when I google for the this string however, I was able to spend some time snooping in the source code and found this line inside the sax.js file on line 105:

if(config.tagName != tagName){
errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName );
}

https://github.com/jindw/xmldom/blob/c033b1907c049ee10a9cc71133925480f03e7134/sax.js

I would be very grateful for any help you could provide on the matter.

All the best,

Ben

Handling of comments seems to be invalid

The code:
// create empty document
var parser = new DOMParser;
var xmldoc = parser.parseFromString('');

// serialize document
var serializer = new XMLSerializer;
var doctxt = serializer.serializeToString(xmldoc);
console.log("xml:",doctxt);

The result:

I don't think it's a good way to serialize comments back.

BTW. the questions is to how to create Document for serialization if exported "classes" are DOMParser and XMLSerializer? Without tricks I can only create document by parsing an empty one

Can not handle &xsd;string case in the xml

Hello,

I used this module for parsing xml file which has the following data.

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE owl [
     <!ENTITY tzont  "http://www.w3.org/2006/timezone#" >
     <!ENTITY owl  "http://www.w3.org/2002/07/owl#" >
     <!ENTITY xsd  "http://www.w3.org/2001/XMLSchema#" >
     <!ENTITY iso "http://www.daml.org/2001/09/countries/iso#" >
     <!ENTITY us-states "http://www.daml.ri.cmu.edu/ont/USRegionState.daml#" >
     <!ENTITY iso-3166-ont "http://www.daml.org/2001/09/countries/iso-3166-ont#" >
   ]>

<rdf:RDF
  xmlns    = "http://www.w3.org/2006/timezone-world#"
  xml:base    = "http://www.w3.org/2006/timezone-world"
  xmlns:tz-world = "http://www.w3.org/2006/timezone-world#"
  xmlns:tzont = "http://www.w3.org/2006/timezone#"
  xmlns:owl = "http://www.w3.org/2002/07/owl#"
  xmlns:rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:rdfs = "http://www.w3.org/2000/01/rdf-schema#"
  xmlns:iso = "http://www.daml.org/2001/09/countries/iso#"
  xmlns:us-states = "http://www.daml.ri.cmu.edu/ont/USRegionState.daml#"
  xmlns:iso-3166-ont = "http://www.daml.org/2001/09/countries/iso-3166-ont#"
  xmlns:xsd = "http://www.w3.org/2001/XMLSchema#">

<!-- intances of time zones -->

  <tzont:TimeZone rdf:ID="YTZ">
    <tzont:name rdf:datatype="&xsd;string">Yankee Time</tzont:name>
    <tzont:name rdf:datatype="&xsd;string">International Date Line West</tzont:name>
    <tzont:GMToffset rdf:datatype="&xsd;duration">-PT12H</tzont:GMToffset>
  </tzont:TimeZone>

</rdf:RDF>

However, all these &xsd; stuff can not be parsed by xmldom. I get this error from sax.js:

entity not found: `&xsd;string`

I think the xml is correct according to xml specification.

Best regards,
Kevin

Create SAX fixture based tests for `jindw/xmldom`.

I couldn't find a conformance suite at analogous to the W3C DOM conformance tests at http://www.saxproject.org/, but Elliotte Rusty Harold has a conformance suite at http://cafeconleche.org/SAXTest/. The fixtures are XML and the test suite can probably be very easily duplicated in JavaScript.

Note that I'm using fixtures to mean data driven and apply the Ruby definition of fixture.

As for the whinging in #4, if the SAX conformance test doesn't say anything about error handling, we could write a fixture generator in Java, one that parses XML and emits errors, with line and column number and we could use that as a fixture to determine when the SAX parser should emit an error. Simply choose the best Java based SAX parser according Elliotte's conformance suite and make that parser the fixture.

As an aside, have a look at the test output of a Travis CI run of Timezone, and toward the end you'll see a test with 35950 assertions, one for the millisecond of and the millisecond before every clock transition in IANA Timezone Database. I run it again against the minified source. I'm mentioning this as an example of a fixture based test.

Update: Fixed link to Timezone Travis CI output.

locator should be enabled by default

When passing in an errorHandler, the line and column numbers are undefined in the error message:

function callback(err) { console.error(err) }
new DOMParser({
    errorHandler: {warning: callback,error:callback,fatalError:callback}
}).parseFromString("<test><", "text/xml")

element parse error: Error: invalid tagName:
@#[line:undefined,col:undefined]

This is fixed by passing in a locator:

new DOMParser({
    errorHandler: {warning: callback,error:callback,fatalError:callback},
    locator: {}
}).parseFromString("<test><", "text/xml")

element parse error: Error: invalid tagName:
@#[line:1,col:7]

I believe this should be the default, or otherwise documented at least.

As a side note, it would also be nice if the error handler received the message and position as separate arguments, for example:

function callback(message, position) {
    console.error(message + " at " + position.line + "#" + position.col);
}

Currently I have to parse the position from the message, which is slightly inconvenient.

Invalid XML document not rejected (e.g. '<r>')

var dp = require('./xmldom').DOMParser;
var assert = require('assert');

var errors = {};

var p = new dp({
errorHandler: function(key,msg){
errors[key] = msg
}
});

var dom = p.parseFromString('', 'text/xml');
assert(errors.error, 'expected error');

getElementsByTagName results are undefined

Example:

var DOMParser = require('xmldom').DOMParser;

var feed = new DOMParser().parseFromString('<feed><entry>foo</entry></feed>');
var entries = feed.documentElement.getElementsByTagName('entry');

console.log(entries[0].nodeName);

...prints "Cannot read property 'nodeName' of undefined".

Running tests - how?

I want to contribute to your library (fix some bugs) and want to add some tests.
But how can I run all the tests which are stored in ./test/ directory at once?

Crash under input xml string which should catch as err

Following code crashes:

var doc = new xmldom.DOMParser({
      errorHandler:function(key,msg){
      console.log(key, msg);
    }
}).parseFromString('<!', 'text/xml');

with err msg:

xmldom/sax.js:480
    var len = matchs.length;
                    ^
TypeError: Cannot read property 'length' of undefined
    at parseDCC (node_modules/xmldom/sax.js:480:19)
    at parse (node_modules/xmldom/sax.js:122:10)
    at Object.XMLReader.parse (node_modules/xmldom/sax.js:30:3)
    at DOMParser.parseFromString (node_modules/xmldom/dom-parser.js:25:7)

Cannot get code working

The simple string is falled to exception
var string="123"
console.log((new DOMParser()).parseFromString(string, "text/xml"));

error "end tag name: root is not match the current start tagName:undefined"

Build on Travis CI.

Always a good thing for a project to have a Travis CI chicklet. I'd like to be able to build on Travis CI before submitting a pull request.

If I were to implement this and submit a pull request, I'd be curious to know @jindw, do you work on Windows or UNIX? If you work on Windows, I'll boot Windows to make sure that you'll be able to do anything build related that I might change in some way.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.