I have an xml document like this,
<Customer ID = "000A551"
Name = "Robert"
Salaried = "yes"
Area = "VA"
/>
Please note the how attributes are line-breaked and white-spaced for the editing and reading convenience. When using XDocument or XmlDocument to modify this document whole formatting goes away. Looks like PreserveWhitespace will only handle significant whitespace.
Is there any way out there to maintain line-breaks and whitespaces ?
No, not handling XML natively. The ‘infoset’ (the data model of XML) does not maintain any record of attribute order or whitespace inside an attribute list. Some XML processors maintain attribute order as a side-effect, but none store whitespace between attributes. It is extremely unusual for anyone to care.
Related
I have an XML Document where it contains data with < character.
<Tunings>
<Notes>Norm <150 mg/dl</Notes>
</Tunings>
The code I am using is:
StreamReader objReader = new StreamReader(strFile);
string strData = objReader.ReadToEnd();
XmlDocument doc = new XmlDocument();
// Here I want to strip those characters from "strData"
doc.LoadXml(strData);
So it gives error:
Name cannot begin with the '1' character, hexadecimal value 0x31.
So is there a way to strip those characters from XML before Load calls.?
If this is only occurring in the <Notes> section, I'd recommend you modify the creation of the XML file to use a CDATA tag to contain the text in Notes, like this:
<Notes><![CDATA[Norm <150 mg/dl]]></Notes>
The CDATA tag tells XML parsers to not parse the characters between the <![CDATA[ and ]]>. This allows you have characters in your XML that would otherwise break the parsing.
You can use the CDATA tag for any situation where you know (or have reasonable expectations) of special characters in that data.
Trying to handle special characters at parsing time (without the CDATA) will be more labor intensive (and frustrating) than simply fixing the creation of the XML in the first place, IMO. Plus, "Norm <150 mg/dl" is not the same thing as "Norm 150 mg/dl", and that distinction might be important for whoever needs that information.
As the comments state, you do not have an XML document. If you know that the only way that these documents deviate from legal XML is as in your example, you could run the file through a regular expression and replace <(?:\d) with &. This will find the < adjacent to a number and properly encode it.
I am using XDocument in LINQ to edit (insert) and save xml document.
XDocument doc = XDocument.Load("c:\\sample.xml", LoadOptions.PreserveWhitespace);
doc.Save("c:\\sample.xml",SaveOptions.DisableFormatting)
sample.xml before doc.Save :
<ELEMENT ATTRIB1="attrib1" ATTRIB2="attrib2" >
value
</ELEMENT>
sample.xml after doc.Save
<ELEMENT ATTRIB1="attrib1" ATTRIB2="attrib2">
value
</ELEMENT>
As you can see, there is double space after ATTRIB1 and a single space after ATTRIB2 in the original document.
But these spaces have been removed by linq when I call doc.save.
How can I preserve the whitespaces inside tag?
I believe that LoadOptions.PreserveWhitespace and SaveOptions.DisableFormatting only instruct XDocument on how to handle whitespace in terms of indentation and the content of text nodes. It would still normalize the attributes, etc.
You may wish to use an overload where you specify an XmlWriter that is configured to do what you want, and if you can't find a configuration that works with the default XmlTextWriter, you could always create your own XmlWriter.
These are "not significant whitespaces" and are removed at the moment of reading the XML. By the time you call save there is no information about spacing between attributes. (Note that strictly speaking even order of attributes may not be known as it has no significance in XML).
If you want to read/write XML in a way that is not directly supported by XML standard you need to provide some custom handling. Depending on requirements custom XmlWriter may be enough (i.e. if you want uniformly separate attributes with 2 whitespaces) or you'll need to build whole stack (readers/writers/nodes) yourself if you want to actually preserve information from original XML (treating it as text, not XML).
UPDATE: The invalid characters are actually in the attributes instead of the elements, this will prevent me from using the CDATA solution as suggested below.
In my application I receive the following XML as a string. There are a two problems with this why this isn't accepted as valid XML.
Hope anyone has a solution for fixing these bug gracefully.
There are ASCII characters in the XML that aren't allowed. Not only the one displayed in the example but I would like to replace all the ASCII code with their corresponding characters.
Within an element the '<' exists - I would like to remove all these entire 'inner elements' (<L CODE="C01">WWW.cars.com</L>) from the XML.
<?xml version="1.0" encoding="ISO-8859-1"?>
<cars>
<car model="ford" description="Argentinië love this"/>
<car model="kia" description="a small family car"/>
<car model="opel" description="great car <L CODE="C01">WWW.cars.com</L>"/>
</cars>
For a quick fix, you could load this not-XML into a string, and add [CDATA][1] markers inside any XML tags that you know usually tend to contain invalid data. For example, if you only ever see bad data inside <description> tags, you could do:
var soCalledXml = ...;
var xml = soCalledXml
.Replace("<description>", "<description><![CDATA[")
.Replace("</description>", "]]></description>");
This would turn the tag into this:
<description><![CDATA[great car <L CODE="C01">WWW.cars.com</L>]]></description>
which you could then process successfully -- it would be a <description> tag that contains the simple string great car <L CODE="C01">WWW.cars.com</L>.
If the <description> tag could ever have any attributes, then this kind of string replacement would be fraught with problems. But if you can count on the open tag to always be exactly the string <description> with no attributes and no extra whitespace inside the tag, and if you can count on the close tag to always be </description> with no whitespace before the >, then this should get you by until you can convince whoever is producing your crap input that they need to produce well-formed XML.
Update
Since the malformed data is inside an attribute, CDATA won't work. But you could use a regular expression to find everything inside those quote characters, and then do string manipulation to properly escape the <s and >s. They're at least escaping embedded quotes, so a regex to go from " to " would work.
Keep in mind that it's generally a bad idea to use regexes on XML. Of course, what you're getting isn't actually XML, but it's still hard to get right for all the same reasons. So expect this to be brittle -- it'll work for your sample input, but it may break when they send you the next file, especially if they don't escape & properly. Your best bet is still to convince them to give you well-formed XML.
using System.Text.RegularExpressions;
var soCalledXml = ...;
var xml = Regex.Replace(soCalledXml, "description=\"[^\"]*\"",
match => match.Value.Replace("<", "<").Replace(">", ">"));
You could wrap that content in a CDATA section.
With regex it will be something like this, match
"<description>(.*?)</description>"
and replace with
"<description><![CDATA[$1]]></description>"
I have an XML well formatted without any spaces. It' must be like that.
When I load it to XMLDocument to sign, the self-closing tags gets an extra white space and
<cEAN/>
becomes:
<cEAN />
Once this document must be signed, it's impossible to remove the white space.
The property PreserveWhiteSpace doesn't made any difference to the result.
How can I change this behavior?
There is no space before the closing "/" in the XmlDocument. XmlDocument is a data structure consisting of nodes. It is binary. It is not text.
Any extra space you are seeing exists only when you serialize the document as text.
Are you actually having a problem with signing, or do you only think you will have such a problem?
I have had this problem before. XML signed by a basic Hash so it can't change when serialized. I solved it by writing a serializer so that I could be sure that it would output the correct XML.
The basic recipe is to Read the XML with a XMLReader, and write out each chunk as it comes.
Try this:
XMLDocument doc;
...
string XMLstring = doc.OuterXml.Replace(" />","/>");
My C# application loads XML documents using the following code:
XmlDocument doc = new XmlDocument();
doc.Load(path);
Some of these documents contain encoded characters, for example:
<xsl:text>
</xsl:text>
I notice that when these documents are loaded,
gets dropped.
My question: How can I preserve <xsl:text>
</xsl:text>?
FYI - The XML declaration used for these documents:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
Are you sure the character is dropped? character 10 is just a line feed- it wouldn't exactly show up in your debugger window. It could also be treated as whitespace. Have you tried playing with the whitespace settings on your xmldocument?
If you need to preserve the encoding you only have two choices: a CDATA section or reading as plain text rather than Xml. I suspect you have absolutely 0 control over the documents that come into the system, therefore eliminating the CDATA option.
Plain-text rather than Xml is probably distasteful as well, but it's all you have left. If you need to do validation or other processing you could first load and verify the xml, and then concatenate your files using simple file streams as a separate step. Again: not ideal, but it's all that's left.
is a linefeed - i.e. whitespace. The XML parser will load it in as a linefeed, and thereafter ignore the fact that it was originally encoded. The encoding is just part of the serialization of the data to text format - it's not part of the data itself.
Now, XML sometimes ignores whitespace and sometimes doesn't, depending on context, API etc. As Joel says you may find that it's not missing at all - or you may find that using it with an API which allows you to preserve whitespace fixes the problem. I wouldn't be at all surprised to see it turned into an unencoded linefeed character when you output the data though.
maybe it would be better to keep data in ![CDATA] ?
http://www.w3schools.com/XML/xml_cdata.asp