2
$\begingroup$
str="<div id=\"1\" style='display:none;'>
<pre class=\"prettyprint lang-mma\">
<pre class=\"Input\" style=\"white-space:nowrap; padding-left:50px;     background-color:#FF359A;\">
<code>
`varCode`
</code>
</pre>
</pre>
</div>";

xml1 = ImportString[str, "XML"]
(*
    XMLObject[Document][{},XMLElement[div,{id->1,style->display:none;},{XMLElement[pre,{class-
>prettyprint lang-mma},{XMLElement[pre,{class->Input,style->white-space:nowrap; padding-le
ft:50px; background-color:#FF359A;},{XMLElement[code,{},{`varCode`}]}]}]}],{}]
*)

We can see the two pre tags are nested, and the result is as expected.

html = ExportString[xml1[[2]], "HTMLFragment"];
Import[Export["test.html", html, "Text"], "XML"]

(*
    <div id="1" style="display:none;"><pre class="prettyprint lang-mma"><pre class="Input" sty
le="white-space:nowrap; padding-left:50px; background-color:#FF359A;"><code>`varCode`</cod
e></pre></pre></div>
*)

Note


In this method of Importing html, two pre tags are not nested.

Import[Export["test.html", html, "Text"], "XMLObject"]

(*
    XMLObject[Document][{XMLObject[Declaration][Version->1.0,Standalone->yes]},XMLElement[html
,{version->-//W3C//DTD HTML 4.01 Transitional//EN,{http://www.w3.org/2000/xmlns/,xmlns}->h
ttp://www.w3.org/1999/xhtml},{XMLElement[body,{},{XMLElement[div,{id->1,style->display:non
e;},{XMLElement[pre,{class->prettyprint lang-mma},{}],XMLElement[pre,{class->Input,style->
white-space:nowrap; padding-left:50px; background-color:#FF359A;},{XMLElement[code,{},{`va
rCode`}]}]}]}]}],{}]
*)

Why using XMLObject? more robust than XML, here is an example, and here is another example.

Many times, Import as XML failed.

My question is why XMLObject is different with XML, and how to Import the HTML file as Nested tags.

Is this a bug or some feature of XMLObject?

$\endgroup$
  • $\begingroup$ You are quiet right. I have absolutely no idea why there is an inconsistency. My best guess is that it has to do with the doctype(or whatever the equivalent is for xml). $\endgroup$ – William Sep 15 '15 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.