Am creating an xml file using xmlwriter,i thought it works fine but when i try to validate it fails bcoz there is spl character (BOM) appears like below,just gone thru forum seen lot of people adive me to use “SecurityElement.Escape”. Am not sure how and where.Some one please guide me to remove this spl charecter from the xml file.
<?xml version="1.0" encoding="utf-8"?>
if found the code for the above symbol
It look like <
My Code
XmlWriter xmlWrite;
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
xmlWrite = XmlWriter.Create(@"c:\test.xml",settings);
xmlWrite.WriteStartElement("metadata");
xmlWrite.WriteElementString("story", story);
xmlWrite.Close();
i can succesfully remove the version but still the spl characters are there . Am stuck now.
Any help ?
This is the Answer to help me to get rid of the spl char
XmlWriter xmlWrite;
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);//Thanks to DaveE
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.OmitXmlDeclaration = true;
xmlWrite = XmlWriter.Create(@"c:\test.xml",settings);
when am append i used “using (TextWriter sw = new StreamWriter(@”c:\test.xml”)) to work it out
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\test.xml");
XmlNode newChild = doc.CreateNode(XmlNodeType.Element, "image", null);
var attribute = doc.CreateAttribute("name");
attribute.Value = nameOnly;
newChild.Attributes.Append(attribute);
XmlNode xmlElement = doc.CreateNode(XmlNodeType.Element, "width", null);
xmlElement.InnerText = widthValue[1].TrimStart();
newChild.AppendChild(xmlElement);
using (TextWriter sw = new StreamWriter(@"C:\test.xml"))
{
doc.Save(sw);
}
When you say you “try to validate it”, what do you mean? XML validators shouldn’t have any trouble with a BOM. And escaping the BOM is going to produce invalid XML.
If you want to us XMLWriterSettings, you need to create it, set the values you want, then use it when you create the XMLWriter. XMLWriter.Settings is read-only.
That doesn’t look like a normal BOM there, btw. Some of the bytes are correct, but there’s junk in it. What code page is set on your system?
EDIT: Add Encoding to your XMLWriterSettings object:
settings.Encoding = new UTF8Encoding(false);The ‘false’ parameter tells the Encoding not to use a BOM.