XML: How to load the contents of one xml file into another

ε祈祈猫儿з 提交于 2019-12-10 11:30:45

问题


I would just like to be able to dynamically write the contents of an xml file from another xml file.

A.XML contains:

<?xml version="1.0"?>
<node>
-Include Contents of b.xml
</node>

B.XML contains:

<anode>
a
</anode>

is there any way to do this in xml?

End product looks like this:

<?xml version="1.0"?>
<node>
  <anode>
    a
  </anode>
</node>

Update from comments:

In xml alone. so that when i view the xml file in a browser it renders correctly


回答1:


Use an external (parsed) general entity to reference b.xml from a.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE node [
<!ENTITY b SYSTEM "b.xml">
]>
<node>
    &b;
</node>

The XML parser will dynamically include the content of b.xml as it parsees a.xml and will produce the XML that you want.

If you load a.xml in IE, it will render correctly.

Note: Some browsers have very strict security policies that cause problems loading referenced XML files from the filesystem and expanding entity references, so it may not work in all browsers if you load a.xml from the filesystem, but may work in more browsers if you load from a URL.




回答2:


When this XML document is opened in a browser:

<?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
<node>
 -Include Contents of b.xml
</node>

With this XSLT stylesheet (other XML document) refered with stylesheet.xsl relative URI:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="node">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:copy-of select="document('B.xml')"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

It's rendered (without any style, or with browser default XML stylesheet) as:

<node>
    <anode>a</anode>
</node>

Note: The processing instruction. I have used xsl:copy-of instruction because I didn't want to confuse you with posible infinite recursion...



来源:https://stackoverflow.com/questions/5821567/xml-how-to-load-the-contents-of-one-xml-file-into-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!