开发者

Combining XmlWriter objects?

开发者 https://www.devze.com 2022-12-13 06:46 出处:网络
The way my application is structured, each component generates output as XML and returns an XmlWriter object. Before rendering the final output to the page, I combine all XML and perform an XSL transf

The way my application is structured, each component generates output as XML and returns an XmlWriter object. Before rendering the final output to the page, I combine all XML and perform an XSL transformation on that object. Below, is a simplified code sample of the application structure.

Does it make sense to combine XmlWriter objects like this? Is there a better way to structure my application? The optimal solution would be one where I didn't have to pass a single XmlWriter instance as a parameter开发者_JS百科 to each component.

function page1Xml() {
 $content = new XmlWriter();
 $content->openMemory();
 $content->startElement('content');
 $content->text('Sample content');
 $content->endElement();
 return $content;
}

function generateSiteMap() {
 $sitemap = new XmlWriter();
 $sitemap->openMemory();
 $sitemap->startElement('sitemap');
 $sitemap->startElement('page');
 $sitemap->writeAttribute('href', 'page1.php');
 $sitemap->text('Page 1');
 $sitemap->endElement();
 $sitemap->endElement();
 return $sitemap;
}

function output($content)
{
 $doc = new XmlWriter();
 $doc->openMemory();
 $doc->writePi('xml-stylesheet', 'type="text/xsl" href="template.xsl"'); 
 $doc->startElement('document');

 $doc->writeRaw( generateSiteMap()->outputMemory() );
 $doc->writeRaw( $content->outputMemory() );

 $doc->endElement();
 $doc->endDocument();

 $output = xslTransform($doc);
 return $output;
}

$content = page1Xml();
echo output($content);

Update:

I may abandon XmlWriter altogether and use DomDocument instead. It is more flexible and it also seemed to perform better (at least on the crude tests I created).


in this architecture i'd rather pass a collection of Writers to output, along the lines of

 function output($ary) {
     .....
     foreach($ary as $w) $doc->writeRaw($w->outputMemory());
     .....
 }

 output(array(page1(), siteMap(), whateverElse()))


I've never actually seen anyone combine XmlWriter objects this way and I don't think it is very efficient for what I am trying to do. I decided the best approach would be to use DOMDocument instead. The difference is: DOMDocument does not generate any XML until you output, whereas XmlWriter is basically a StringBuilder and is not as flexible.


I would have page1Xml and generateSiteMap get a writer as input, and return it as output

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号