convert < to < xml document
I have read an XML file and converted into NSXMLDocument object. But, due to the presence of "<" in t开发者_JAVA技巧he string content of a node, it has been converted into "<". So, when i write it as xml document to a file, it has the character "<" in it.
How can i write to the file as ordinary XML file in which "<" will be replaced by "<".
Thanks and Regards, Lenin
When the <
character appears in a text node, it will be serialized as <
when you write your xml to a file.
When you later read that file with an xml parser, the text node will contain the original <
character.
You also have the option of CDATA encoding the text node. In this case the serialized character is <
inside a CDATA block. Many XML APIs will not retain any difference between CDATA and text nodes. CDATA should be thought of as an escaping mechanism to make editing easy for human authors.
The <
in text nodes of an xml should be represented as <
.
If you replace it using s/</</g
before writing it to the xml file, it will lead to parsing error when you read from that file.
You can use following function for doing the vice versa operation
htmlspecialchars and
htmlentities()
The <
character must be escaped when it's not part of an XML tag (see here). You really shouldn't break the XML spec...
However, if you must, you can perform a trick before writing your XML document:
- Replace your instances of
<
with a unique string that won't be escaped by your XML parser (something that you know occurs nowhere else in the file). Something like*-lt-*
will probably do. - Have the parser produce the file & save it.
- Read in the file as
plaintext, and replace your instances
of
*-lt-*
with the regular<
character. - Re-write the file, clobbering the version that was written by the XML parser.
Again, it's a terrible idea to break the XML spec... by doing this, no parser will be able to read your new XML document.
If you want to replace < to < in XML document via php:
$xmlFile = file_get_contents("example.xml");
$xml= str_replace(['<','>'],['<','>'], $xmlFile);
echo $xml;
I am getting news feed from a server via XML and then store it to another xml file, I'm geting the result with <
and >
so I used this method. It's not a smartest way to store XML but I am not a pro mega senior back ender either.
精彩评论