简体   繁体   中英

Multiple xml elements in the same xml file

In a xml file this ok:

<target name="test">
    <exec executable="app">
        <arg value="run"/>
        <arg value="stop"/>
    </exec>     
</target>

But having having this in a xml file is not (at least that is what validation says):

<target name="test">
    <exec executable="app">
        <arg value="run"/>
        <arg value="stop"/>
    </exec>     
</target>
<target name="test">
    <exec executable="app">
        <arg value="run"/>
        <arg value="stop"/>
    </exec>     
</target>

Why is it illegal to have multiple target elements in the same xml file after each other?

"Why" questions are hard to answer. Partly it is that way in XML because it was in SGML. Enforcing a single document container element does have some advantages, although the main possible advantage; that you know when you have got to the end, is somewhat spoiled by the fact that there can be comments and processing instructions after the end of the root element.

It is somewhat a pain if you want to use XML format in streaming context such as log files where you want to keep adding an element to the end.

A common solution to that problem is to observe that the file with multiple top level elements is not a well formed document but it is a well formed external parsed entity . So if you generate a file log.xml with dozens of top level elements then you cannot parse that as a document but you can make one static small document that references the external parsed entity log.xml and you are back on specified territory.

wrapper.xml

<!DOCTYPE wrapper [
<!ENTITY thelog SYSTEM "log.xml">
]>
<wrapper>
&thelog;
</wrapper>

then if you parse wrapper.xml the parser will construct a document with a root element wrapper containing all the elements that were in the file log.xml .

Because a valid xml file should have one (and only one) root element.

See the root element article from wikipedia or this W3C recommandation paper from which I extracted this quote :

[Definition: There is exactly one element, called the root, or document element, no part of which appears in the content of any other element.]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM