bug 190098, txXMLParser should load DTDs on standalone, pretty much a rewrite of how parsing to a DOM works on standalone, copying what nsExpatDriver does, optimize id patterns, too, r=sicking, sr=peterv

This commit is contained in:
axel%pike.org 2003-03-05 13:48:55 +00:00
Родитель 941dfeb487
Коммит 4ab4b70601
14 изменённых файлов: 590 добавлений и 61 удалений

Просмотреть файл

@ -1316,7 +1316,7 @@
</FILE> </FILE>
<FILE> <FILE>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>XMLParser.cpp</PATH> <PATH>txXMLParser.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
<FILEKIND>Text</FILEKIND> <FILEKIND>Text</FILEKIND>
<FILEFLAGS></FILEFLAGS> <FILEFLAGS></FILEFLAGS>
@ -1795,7 +1795,7 @@
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>XMLParser.cpp</PATH> <PATH>txXMLParser.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
@ -3180,7 +3180,7 @@
</FILE> </FILE>
<FILE> <FILE>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>XMLParser.cpp</PATH> <PATH>txXMLParser.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
<FILEKIND>Text</FILEKIND> <FILEKIND>Text</FILEKIND>
<FILEFLAGS></FILEFLAGS> <FILEFLAGS></FILEFLAGS>
@ -3667,7 +3667,7 @@
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>XMLParser.cpp</PATH> <PATH>txXMLParser.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
</FILEREF> </FILEREF>
<FILEREF> <FILEREF>
@ -3945,7 +3945,7 @@
<FILEREF> <FILEREF>
<TARGETNAME>transformiixDebug.shlb</TARGETNAME> <TARGETNAME>transformiixDebug.shlb</TARGETNAME>
<PATHTYPE>Name</PATHTYPE> <PATHTYPE>Name</PATHTYPE>
<PATH>XMLParser.cpp</PATH> <PATH>txXMLParser.cpp</PATH>
<PATHFORMAT>MacOS</PATHFORMAT> <PATHFORMAT>MacOS</PATHFORMAT>
</FILEREF> </FILEREF>
</GROUP> </GROUP>

Просмотреть файл

@ -81,7 +81,7 @@ OBJS = ../base/Double.$(OBJ_SUFFIX) \
../xpath/VariableRefExpr.$(OBJ_SUFFIX) \ ../xpath/VariableRefExpr.$(OBJ_SUFFIX) \
../xml/XMLUtils.$(OBJ_SUFFIX) \ ../xml/XMLUtils.$(OBJ_SUFFIX) \
../xml/XMLDOMUtils.$(OBJ_SUFFIX) \ ../xml/XMLDOMUtils.$(OBJ_SUFFIX) \
../xml/parser/XMLParser.$(OBJ_SUFFIX) \ ../xml/parser/txXMLParser.$(OBJ_SUFFIX) \
../xslt/txOutputFormat.$(OBJ_SUFFIX) \ ../xslt/txOutputFormat.$(OBJ_SUFFIX) \
../xslt/ProcessorState.$(OBJ_SUFFIX) \ ../xslt/ProcessorState.$(OBJ_SUFFIX) \
../xslt/txHTMLOutput.$(OBJ_SUFFIX) \ ../xslt/txHTMLOutput.$(OBJ_SUFFIX) \

Просмотреть файл

@ -39,6 +39,7 @@
// //
Document::Document() : NodeDefinition(Node::DOCUMENT_NODE, nsString(), NULL) Document::Document() : NodeDefinition(Node::DOCUMENT_NODE, nsString(), NULL)
{ {
mIDMap.Init(0);
documentElement = nsnull; documentElement = nsnull;
} }
@ -118,15 +119,32 @@ ProcessingInstruction*
// //
//Return an Element by ID, introduced by DOM2 //Return an Element by ID, introduced by DOM2
// //
DHASH_WRAPPER(txIDMap, txIDEntry, const nsAString&)
Element* Document::getElementById(const nsAString& aID) Element* Document::getElementById(const nsAString& aID)
{ {
/* This would need knowledge of the DTD, and we don't have it. txIDEntry* entry = mIDMap.GetEntry(aID);
* If we knew that we deal with HTML4 or XHTML1 we could check if (entry)
* for the "id" attribute, but we don't, so return NULL return entry->mElement;
*/
return nsnull; return nsnull;
} }
/**
* private setter for element ID
*/
PRBool
Document::setElementID(const nsAString& aID, Element* aElement)
{
txIDEntry* id = mIDMap.AddEntry(aID);
// make sure IDs are unique
if (id->mElement) {
return PR_FALSE;
}
id->mElement = aElement;
id->mElement->setIDValue(aID);
return PR_TRUE;
}
Node* Document::appendChild(Node* newChild) Node* Document::appendChild(Node* newChild)
{ {
unsigned short nodeType = newChild->getNodeType(); unsigned short nodeType = newChild->getNodeType();

Просмотреть файл

@ -254,3 +254,22 @@ MBool Element::hasAttr(nsIAtom* aLocalName, PRInt32 aNSID)
} }
return MB_FALSE; return MB_FALSE;
} }
/**
* ID accessors. Getter used for id() patterns, private setter for parser
*/
PRBool
Element::getIDValue(nsAString& aValue)
{
if (mIDValue.IsEmpty()) {
return PR_FALSE;
}
aValue = mIDValue;
return PR_TRUE;
}
void
Element::setIDValue(const nsAString& aValue)
{
mIDValue = aValue;
}

Просмотреть файл

@ -41,6 +41,7 @@
#include "List.h" #include "List.h"
#include "nsIAtom.h" #include "nsIAtom.h"
#include "baseutils.h" #include "baseutils.h"
#include "nsDoubleHashtable.h"
#include "nsString.h" #include "nsString.h"
#include "nsVoidArray.h" #include "nsVoidArray.h"
@ -359,6 +360,29 @@ class DocumentFragment : public NodeDefinition
// //
//Definition and Implementation of a Document. //Definition and Implementation of a Document.
// //
/**
* nsDoubleHashtable definitions for IDs
*
* It may be possible to share the key value with the element,
* but that may leave entries without keys, as the entries
* are constructed from the key value and the setting of mElement
* happens late. As pldhash.h ain't clear on this, we store the
* key by inheriting from PLDHashStringEntry.
*/
class txIDEntry : public PLDHashStringEntry
{
public:
txIDEntry(const void* aKey) : PLDHashStringEntry(aKey), mElement(nsnull)
{
}
~txIDEntry()
{
}
Element* mElement;
};
DECL_DHASH_WRAPPER(txIDMap, txIDEntry, const nsAString&)
class Document : public NodeDefinition class Document : public NodeDefinition
{ {
public: public:
@ -393,10 +417,14 @@ class Document : public NodeDefinition
void namespaceIDToURI(PRInt32 aNamespaceID, nsAString& aNamespaceURI); void namespaceIDToURI(PRInt32 aNamespaceID, nsAString& aNamespaceURI);
private: private:
PRBool setElementID(const nsAString& aID, Element* aElement);
Element* documentElement; Element* documentElement;
// This class is friend to be able to set the documentBaseURI // This class is friend to be able to set the documentBaseURI
friend class XMLParser; // and IDs.
friend class txXMLParser;
txIDMap mIDMap;
nsString documentBaseURI; nsString documentBaseURI;
}; };
@ -424,13 +452,18 @@ class Element : public NodeDefinition
MBool getAttr(nsIAtom* aLocalName, PRInt32 aNSID, nsAString& aValue); MBool getAttr(nsIAtom* aLocalName, PRInt32 aNSID, nsAString& aValue);
MBool hasAttr(nsIAtom* aLocalName, PRInt32 aNSID); MBool hasAttr(nsIAtom* aLocalName, PRInt32 aNSID);
// ID getter
PRBool getIDValue(nsAString& aValue);
private: private:
friend class Document; friend class Document;
void setIDValue(const nsAString& aValue);
Element(const nsAString& tagName, Document* owner); Element(const nsAString& tagName, Document* owner);
Element(const nsAString& aNamespaceURI, const nsAString& aTagName, Element(const nsAString& aNamespaceURI, const nsAString& aTagName,
Document* aOwner); Document* aOwner);
AttrMap mAttributes; AttrMap mAttributes;
nsString mIDValue;
nsCOMPtr<nsIAtom> mLocalName; nsCOMPtr<nsIAtom> mLocalName;
PRInt32 mNamespaceID; PRInt32 mNamespaceID;
}; };

Просмотреть файл

@ -46,10 +46,12 @@ REQUIRES = string \
$(NULL) $(NULL)
endif endif
CPPSRCS = XMLParser.cpp CPPSRCS = txXMLParser.cpp
include $(topsrcdir)/config/rules.mk include $(topsrcdir)/config/rules.mk
DEFINES += -DXML_DTD -DXML_UNICODE
INCLUDES += -I$(srcdir)/../../base -I$(srcdir)/../dom INCLUDES += -I$(srcdir)/../../base -I$(srcdir)/../dom
libs:: $(OBJS) libs:: $(OBJS)

Просмотреть файл

Просмотреть файл

Просмотреть файл

@ -0,0 +1,413 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is TransforMiiX XSLT processor.
*
* The Initial Developer of the Original Code is The MITRE Corporation.
* Portions created by MITRE are Copyright (C) 1999 The MITRE Corporation.
*
* Portions created by Keith Visco as a Non MITRE employee,
* (C) 1999 Keith Visco. All Rights Reserved.
*
* Contributor(s):
* Tom Kneeland, tomk@mitre.org
* -- original author.
*/
#include "txXMLParser.h"
#include "txURIUtils.h"
#ifndef TX_EXE
#include "nsIDocument.h"
#include "nsIDOMDocument.h"
#include "nsISyncLoadDOMService.h"
#include "nsNetUtil.h"
#else
#include "xmlparse.h"
#endif
#ifdef TX_EXE
/**
* Implementation of an In-Memory DOM based XML parser. The actual XML
* parsing is provided by EXPAT.
*/
class txXMLParser
{
public:
nsresult parse(istream& aInputStream, const nsAString& aUri,
Document** aResultDoc);
const nsAString& getErrorString();
/**
* Expat handlers
*/
int StartElement(const XML_Char *aName, const XML_Char **aAtts);
int EndElement(const XML_Char* aName);
void CharacterData(const XML_Char* aChars, int aLength);
void Comment(const XML_Char* aChars);
int ProcessingInstruction(const XML_Char *aTarget, const XML_Char *aData);
int ExternalEntityRef(const XML_Char *aContext, const XML_Char *aBase,
const XML_Char *aSystemId,
const XML_Char *aPublicId);
protected:
void createErrorString();
nsString mErrorString;
Document* mDocument;
Node* mCurrentNode;
XML_Parser mExpatParser;
};
#endif
nsresult
txParseDocumentFromURI(const nsAString& aHref, const nsAString& aReferrer,
Document* aLoader, nsAString& aErrMsg,
Document** aResult)
{
NS_ENSURE_ARG_POINTER(aResult);
*aResult = nsnull;
#ifndef TX_EXE
nsCOMPtr<nsIURI> documentURI;
nsresult rv = NS_NewURI(getter_AddRefs(documentURI), aHref);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIDOMDocument> theDocument;
nsCOMPtr<nsIDocument> loaderDocument =
do_QueryInterface(aLoader->getNSObj());
nsCOMPtr<nsILoadGroup> loadGroup;
nsCOMPtr<nsIURI> loaderUri;
loaderDocument->GetDocumentLoadGroup(getter_AddRefs(loadGroup));
loaderDocument->GetDocumentURL(getter_AddRefs(loaderUri));
NS_ENSURE_TRUE(loaderUri, NS_ERROR_FAILURE);
nsCOMPtr<nsIChannel> channel;
rv = NS_NewChannel(getter_AddRefs(channel), documentURI, nsnull,
loadGroup);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIHttpChannel> http = do_QueryInterface(channel);
if (http) {
nsCOMPtr<nsIURI> refUri;
NS_NewURI(getter_AddRefs(refUri), aReferrer);
if (refUri) {
http->SetReferrer(refUri);
}
http->SetRequestHeader(NS_LITERAL_CSTRING("Accept"),
NS_LITERAL_CSTRING("text/xml,application/xml,application/xhtml+xml,*/*;q=0.1"),
PR_FALSE);
}
nsCOMPtr<nsISyncLoadDOMService> loader =
do_GetService("@mozilla.org/content/syncload-dom-service;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = loader->LoadDocument(channel, loaderUri, getter_AddRefs(theDocument));
if (NS_FAILED(rv) || !theDocument) {
aErrMsg.Append(NS_LITERAL_STRING("Document load of ") +
aHref + NS_LITERAL_STRING(" failed."));
return rv;
}
*aResult = new Document(theDocument);
if (!*aResult) {
return NS_ERROR_FAILURE;
}
return NS_OK;
#else
istream* xslInput = URIUtils::getInputStream(aHref, aErrMsg);
if (!xslInput) {
return NS_ERROR_FAILURE;
}
return txParseFromStream(*xslInput, aHref, aErrMsg, aResult);
#endif
}
#ifdef TX_EXE
nsresult
txParseFromStream(istream& aInputStream, const nsAString& aUri,
nsAString& aErrorString, Document** aResult)
{
NS_ENSURE_ARG_POINTER(aResult);
txXMLParser parser;
nsresult rv = parser.parse(aInputStream, aUri, aResult);
aErrorString = parser.getErrorString();
return rv;
}
/**
* expat C stub handlers
*/
// shortcut macro for redirection into txXMLParser method calls
#define TX_XMLPARSER(_userData) NS_STATIC_CAST(txXMLParser*, _userData)
PR_STATIC_CALLBACK(int)
startElement(void *aUserData, const XML_Char *aName, const XML_Char **aAtts)
{
NS_ENSURE_TRUE(aUserData, XML_ERROR_NONE);
return TX_XMLPARSER(aUserData)->StartElement(aName, aAtts);
}
PR_STATIC_CALLBACK(int)
endElement(void *aUserData, const XML_Char* aName)
{
NS_ENSURE_TRUE(aUserData, XML_ERROR_NONE);
return TX_XMLPARSER(aUserData)->EndElement(aName);
}
PR_STATIC_CALLBACK(void)
charData(void* aUserData, const XML_Char* aChars, int aLength)
{
if (!aUserData) {
NS_WARNING("no userData in charData handler");
return;
}
TX_XMLPARSER(aUserData)->CharacterData(aChars, aLength);
}
PR_STATIC_CALLBACK(void)
commentHandler(void* aUserData, const XML_Char* aChars)
{
if (!aUserData) {
NS_WARNING("no userData in comment handler");
return;
}
TX_XMLPARSER(aUserData)->Comment(aChars);
}
PR_STATIC_CALLBACK(int)
piHandler(void *aUserData, const XML_Char *aTarget, const XML_Char *aData)
{
NS_ENSURE_TRUE(aUserData, XML_ERROR_NONE);
return TX_XMLPARSER(aUserData)->ProcessingInstruction(aTarget, aData);
}
PR_STATIC_CALLBACK(int)
externalEntityRefHandler(XML_Parser aParser,
const XML_Char *aContext,
const XML_Char *aBase,
const XML_Char *aSystemId,
const XML_Char *aPublicId)
{
// aParser is aUserData is the txXMLParser,
// we set that in txXMLParser::parse
NS_ENSURE_TRUE(aParser, XML_ERROR_NONE);
return TX_XMLPARSER(aParser)->ExternalEntityRef(aContext, aBase,
aSystemId, aPublicId);
}
/**
* Parses the given input stream and returns a DOM Document.
* A NULL pointer will be returned if errors occurred
*/
nsresult
txXMLParser::parse(istream& aInputStream, const nsAString& aUri,
Document** aResultDoc)
{
mErrorString.Truncate();
*aResultDoc = nsnull;
if (!aInputStream) {
mErrorString.Append(NS_LITERAL_STRING("unable to parse xml: invalid or unopen stream encountered."));
return NS_ERROR_FAILURE;
}
mExpatParser = XML_ParserCreate(nsnull);
if (!mExpatParser) {
return NS_ERROR_OUT_OF_MEMORY;
}
mDocument = new Document();
if (!mDocument) {
XML_ParserFree(mExpatParser);
return NS_ERROR_OUT_OF_MEMORY;
}
mDocument->documentBaseURI = aUri;
mCurrentNode = mDocument;
XML_SetUserData(mExpatParser, this);
XML_SetElementHandler(mExpatParser, startElement, endElement);
XML_SetCharacterDataHandler(mExpatParser, charData);
XML_SetProcessingInstructionHandler(mExpatParser, piHandler);
XML_SetCommentHandler(mExpatParser, commentHandler);
#ifdef XML_DTD
XML_SetParamEntityParsing(mExpatParser, XML_PARAM_ENTITY_PARSING_ALWAYS);
#endif
XML_SetExternalEntityRefHandler(mExpatParser, externalEntityRefHandler);
XML_SetExternalEntityRefHandlerArg(mExpatParser, this);
XML_SetBase(mExpatParser,
(const XML_Char*)(PromiseFlatString(aUri).get()));
const int bufferSize = 1024;
char buf[bufferSize];
PRBool done;
do {
aInputStream.read(buf, bufferSize);
done = aInputStream.eof();
if (!XML_Parse(mExpatParser, buf, aInputStream.gcount(), done)) {
createErrorString();
done = MB_TRUE;
delete mDocument;
mDocument = nsnull;
}
} while (!done);
aInputStream.clear();
// clean up
XML_ParserFree(mExpatParser);
// ownership to the caller
*aResultDoc = mDocument;
mDocument = nsnull;
return NS_OK;
}
const nsAString&
txXMLParser::getErrorString()
{
return mErrorString;
}
int
txXMLParser::StartElement(const XML_Char *aName, const XML_Char **aAtts)
{
const XML_Char** theAtts = aAtts;
Element* newElement =
mDocument->createElement(nsDependentString((const PRUnichar*)aName));
if (!newElement) {
return XML_ERROR_NO_MEMORY;
}
while (*theAtts) {
nsDependentString attName((const PRUnichar*)*theAtts++);
nsDependentString attValue((const PRUnichar*)*theAtts++);
newElement->setAttribute(attName, attValue);
}
int idx;
if ((idx = XML_GetIdAttributeIndex(mExpatParser)) > -1) {
nsDependentString idName((const PRUnichar*)*(aAtts + idx));
nsDependentString idValue((const PRUnichar*)*(aAtts + idx + 1));
// make sure IDs are unique
if (!idValue.IsEmpty()) {
mDocument->setElementID(idValue, newElement);
}
}
mCurrentNode->appendChild(newElement);
mCurrentNode = newElement;
return XML_ERROR_NONE;
}
int
txXMLParser::EndElement(const XML_Char* aName)
{
if (mCurrentNode->getParentNode()) {
mCurrentNode = mCurrentNode->getParentNode();
}
return XML_ERROR_NONE;
}
void
txXMLParser::CharacterData(const XML_Char* aChars, int aLength)
{
Node* prevSib = mCurrentNode->getLastChild();
const PRUnichar* pChars = NS_STATIC_CAST(const PRUnichar*, aChars);
if (prevSib && prevSib->getNodeType() == Node::TEXT_NODE) {
NS_STATIC_CAST(NodeDefinition*, prevSib)->appendData(pChars, aLength);
}
else {
// aChars is not null-terminated so we use Substring here.
Node* node = mDocument->createTextNode(Substring(pChars,
pChars + aLength));
mCurrentNode->appendChild(node);
}
}
void
txXMLParser::Comment(const XML_Char* aChars)
{
Node* node = mDocument->createComment(
nsDependentString(NS_STATIC_CAST(const PRUnichar*, aChars)));
mCurrentNode->appendChild(node);
}
int
txXMLParser::ProcessingInstruction(const XML_Char *aTarget,
const XML_Char *aData)
{
nsDependentString target((const PRUnichar*)aTarget);
nsDependentString data((const PRUnichar*)aData);
Node* node = mDocument->createProcessingInstruction(target, data);
mCurrentNode->appendChild(node);
return XML_ERROR_NONE;
}
int
txXMLParser::ExternalEntityRef(const XML_Char *aContext,
const XML_Char *aBase,
const XML_Char *aSystemId,
const XML_Char *aPublicId)
{
if (aPublicId) {
// not supported, this is "http://some.site.net/foo.dtd" stuff
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
}
nsAutoString absUrl;
URIUtils::resolveHref(nsDependentString((PRUnichar*)aSystemId),
nsDependentString((PRUnichar*)aBase), absUrl);
istream* extInput = URIUtils::getInputStream(absUrl, mErrorString);
if (!extInput) {
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
}
XML_Parser parent = mExpatParser;
mExpatParser =
XML_ExternalEntityParserCreate(mExpatParser, aContext, nsnull);
if (!mExpatParser) {
mExpatParser = parent;
delete extInput;
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
}
XML_SetBase(mExpatParser, absUrl.get());
const int bufSize = 1024;
char buffer[bufSize];
int result;
PRBool done;
do {
extInput->read(buffer, bufSize);
done = extInput->eof();
if (!(result =
XML_Parse(mExpatParser, buffer, extInput->gcount(), done))) {
createErrorString();
mErrorString.Append(PRUnichar('\n'));
done = MB_TRUE;
}
} while (!done);
delete extInput;
XML_ParserFree(mExpatParser);
mExpatParser = parent;
return result;
}
void
txXMLParser::createErrorString()
{
XML_Error errCode = XML_GetErrorCode(mExpatParser);
mErrorString.AppendWithConversion(XML_ErrorString(errCode));
mErrorString.Append(NS_LITERAL_STRING(" at line "));
mErrorString.AppendInt(XML_GetCurrentLineNumber(mExpatParser));
mErrorString.Append(NS_LITERAL_STRING(" in "));
mErrorString.Append((const PRUnichar*)XML_GetBase(mExpatParser));
}
#endif

Просмотреть файл

@ -0,0 +1,56 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is TransforMiiX XSLT processor.
*
* The Initial Developer of the Original Code is The MITRE Corporation.
* Portions created by MITRE are Copyright (C) 1999 The MITRE Corporation.
*
* Portions created by Keith Visco as a Non MITRE employee,
* (C) 1999 Keith Visco. All Rights Reserved.
*
* Contributor(s):
* Tom Kneeland
* -- original author.
*/
#ifndef MITRE_XMLPARSER_H
#define MITRE_XMLPARSER_H
#include "dom.h"
#ifdef TX_EXE
#include <iostream.h>
#endif
/**
* API to load XML files into DOM datastructures.
* Parsing is either done by expat, or by expat via the synchloaderservice
*/
/**
* Parse a document from the aHref location, with referrer URI on behalf
* of the document aLoader.
*/
extern "C" nsresult
txParseDocumentFromURI(const nsAString& aHref, const nsAString& aReferrer,
Document* aLoader, nsAString& aErrMsg,
Document** aResult);
#ifdef TX_EXE
/**
* Parse a document from the given stream
*/
extern "C" nsresult
txParseFromStream(istream& aInputStream, const nsAString& aUri,
nsAString& aErrorString, Document** aResult);
#endif
#endif

Просмотреть файл

@ -39,7 +39,7 @@
#include "XMLUtils.h" #include "XMLUtils.h"
#include "XMLDOMUtils.h" #include "XMLDOMUtils.h"
#include "ExprResult.h" #include "ExprResult.h"
#include "XMLParser.h" #include "txXMLParser.h"
#include "TxLog.h" #include "TxLog.h"
#include "txAtoms.h" #include "txAtoms.h"
#include "txSingleNodeContext.h" #include "txSingleNodeContext.h"
@ -445,14 +445,16 @@ Node* ProcessorState::retrieveDocument(const nsAString& uri,
if (!xmlDoc) { if (!xmlDoc) {
// open URI // open URI
nsAutoString errMsg; nsAutoString errMsg, refUri;
XMLParser xmlParser; // XXX we should get the referrer from the actual node
// triggering the load, but this will do for the time being
mLoadedDocuments.mStyleDocument->getBaseURI(refUri);
nsresult rv;
rv = txParseDocumentFromURI(docUrl, refUri,
mLoadedDocuments.mStyleDocument, errMsg,
&xmlDoc);
xmlDoc = xmlParser.getDocumentFromURI(docUrl, if (NS_FAILED(rv) || !xmlDoc) {
mLoadedDocuments.mStyleDocument,
errMsg);
if (!xmlDoc) {
receiveError(NS_LITERAL_STRING("Couldn't load document '") + receiveError(NS_LITERAL_STRING("Couldn't load document '") +
docUrl + NS_LITERAL_STRING("': ") + errMsg, docUrl + NS_LITERAL_STRING("': ") + errMsg,
NS_ERROR_XSLT_INVALID_URL); NS_ERROR_XSLT_INVALID_URL);

Просмотреть файл

@ -46,7 +46,7 @@
#include "txTextOutput.h" #include "txTextOutput.h"
#include "txUnknownHandler.h" #include "txUnknownHandler.h"
#include "txURIUtils.h" #include "txURIUtils.h"
#include "XMLParser.h" #include "txXMLParser.h"
/** /**
* Output Handler Factory * Output Handler Factory
@ -378,11 +378,13 @@ txStandaloneXSLTProcessor::parsePath(const nsACString& aPath, ErrorObserver& aEr
return 0; return 0;
} }
// parse source // parse source
XMLParser xmlParser; Document* xmlDoc;
Document* xmlDoc = xmlParser.parse(xmlInput, path); nsAutoString errors;
nsresult rv = txParseFromStream(xmlInput, path, errors, &xmlDoc);
xmlInput.close(); xmlInput.close();
if (!xmlDoc) { if (NS_FAILED(rv) || !xmlDoc) {
aErr.receiveError(NS_LITERAL_STRING("Parsing error in ") + path); aErr.receiveError(NS_LITERAL_STRING("Parsing error \"") + errors +
NS_LITERAL_STRING("\""));
} }
return xmlDoc; return xmlDoc;
} }

Просмотреть файл

@ -36,16 +36,16 @@
* *
* ***** END LICENSE BLOCK ***** */ * ***** END LICENSE BLOCK ***** */
#include "nsReadableUtils.h"
#include "ProcessorState.h"
#include "txXSLTPatterns.h" #include "txXSLTPatterns.h"
#include "txNodeSetContext.h" #include "txNodeSetContext.h"
#include "txForwardContext.h" #include "txForwardContext.h"
#include "XMLUtils.h"
#include "XSLTFunctions.h" #include "XSLTFunctions.h"
#include "ProcessorState.h"
#ifndef TX_EXE #ifndef TX_EXE
#include "nsReadableUtils.h"
#include "nsIContent.h" #include "nsIContent.h"
#include "nsINodeInfo.h" #include "nsINodeInfo.h"
#include "XMLUtils.h"
#endif #endif
/* /*
@ -320,9 +320,6 @@ void txRootPattern::toString(nsAString& aDest)
*/ */
txIdPattern::txIdPattern(const nsAString& aString) txIdPattern::txIdPattern(const nsAString& aString)
{ {
#ifdef TX_EXE
mIds = aString;
#else
nsAString::const_iterator pos, begin, end; nsAString::const_iterator pos, begin, end;
aString.BeginReading(begin); aString.BeginReading(begin);
aString.EndReading(end); aString.EndReading(end);
@ -331,13 +328,11 @@ txIdPattern::txIdPattern(const nsAString& aString)
while (pos != end && XMLUtils::isWhitespace(*pos)) while (pos != end && XMLUtils::isWhitespace(*pos))
++pos; ++pos;
begin = pos; begin = pos;
if (!mIds.IsEmpty())
mIds += PRUnichar(' ');
while (pos != end && !XMLUtils::isWhitespace(*pos)) while (pos != end && !XMLUtils::isWhitespace(*pos))
++pos; ++pos;
mIds += Substring(begin, pos); // this can fail, XXX move to a Init(aString) method
mIds.AppendString(Substring(begin, pos));
} }
#endif
} }
txIdPattern::~txIdPattern() txIdPattern::~txIdPattern()
@ -346,15 +341,16 @@ txIdPattern::~txIdPattern()
MBool txIdPattern::matches(Node* aNode, txIMatchContext* aContext) MBool txIdPattern::matches(Node* aNode, txIMatchContext* aContext)
{ {
#ifdef TX_EXE
return MB_FALSE; // not implemented
#else
if (aNode->getNodeType() != Node::ELEMENT_NODE) { if (aNode->getNodeType() != Node::ELEMENT_NODE) {
return MB_FALSE; return MB_FALSE;
} }
// Get a ID attribute, if there is // Get a ID attribute, if there is
nsAutoString value;
#ifdef TX_EXE
if (!((Element*)aNode)->getIDValue(value))
return MB_FALSE;
#else
nsCOMPtr<nsIContent> content = do_QueryInterface(aNode->getNSObj()); nsCOMPtr<nsIContent> content = do_QueryInterface(aNode->getNSObj());
NS_ASSERTION(content, "a Element without nsIContent"); NS_ASSERTION(content, "a Element without nsIContent");
if (!content) { if (!content) {
@ -370,31 +366,12 @@ MBool txIdPattern::matches(Node* aNode, txIMatchContext* aContext)
if (!idAttr) { if (!idAttr) {
return MB_FALSE; // no ID for this element defined, can't match return MB_FALSE; // no ID for this element defined, can't match
} }
nsAutoString value;
nsresult rv = content->GetAttr(kNameSpaceID_None, idAttr, value); nsresult rv = content->GetAttr(kNameSpaceID_None, idAttr, value);
if (rv != NS_CONTENT_ATTR_HAS_VALUE) { if (rv != NS_CONTENT_ATTR_HAS_VALUE) {
return MB_FALSE; // no ID attribute given return MB_FALSE; // no ID attribute given
} }
nsAString::const_iterator pos, begin, end;
mIds.BeginReading(begin);
mIds.EndReading(end);
pos = begin;
const PRUnichar space = PRUnichar(' ');
PRBool found = FindCharInReadable(space, pos, end);
while (found) {
if (value.Equals(Substring(begin, pos))) {
return MB_TRUE;
}
++pos; // skip ' '
begin = pos;
found = FindCharInReadable(PRUnichar(' '), pos, end);
}
if (value.Equals(Substring(begin, pos))) {
return MB_TRUE;
}
return MB_FALSE;
#endif // TX_EXE #endif // TX_EXE
return mIds.IndexOf(value) > -1;
} }
double txIdPattern::getDefaultPriority() double txIdPattern::getDefaultPriority()
@ -408,7 +385,12 @@ void txIdPattern::toString(nsAString& aDest)
aDest.Append(NS_LITERAL_STRING("txIdPattern{")); aDest.Append(NS_LITERAL_STRING("txIdPattern{"));
#endif #endif
aDest.Append(NS_LITERAL_STRING("id('")); aDest.Append(NS_LITERAL_STRING("id('"));
aDest.Append(mIds); PRUint32 k, count = mIds.Count() - 1;
for (k = 0; k < count; ++k) {
aDest.Append(*mIds[k]);
aDest.Append(PRUnichar(' '));
}
aDest.Append(*mIds[count]);
aDest.Append(NS_LITERAL_STRING("')")); aDest.Append(NS_LITERAL_STRING("')"));
#ifdef DEBUG #ifdef DEBUG
aDest.Append(PRUnichar('}')); aDest.Append(PRUnichar('}'));

Просмотреть файл

@ -41,6 +41,8 @@
#include "Expr.h" #include "Expr.h"
#include "XMLUtils.h" #include "XMLUtils.h"
#include "nsVoidArray.h"
class ProcessorState; class ProcessorState;
class txPattern : public TxObject class txPattern : public TxObject
@ -166,7 +168,7 @@ public:
TX_DECL_PATTERN; TX_DECL_PATTERN;
private: private:
nsString mIds; nsStringArray mIds;
}; };
class txKeyPattern : public txPattern class txKeyPattern : public txPattern