Remove standalone attribute from xml file - c#

I have an xml file which I need to modify and write it back to an outputfile.
The problem is that the result outputfile contains an extra attribute 'standalone' in the root declartion which does not exist in the original inputfile.
Is there any way how I can prevent from XmlDocument adding this attribute ?
The code I have tried:
//read input xml
XmlDocument xDoc = new XmlDocument();
xDoc.Load(originalFile);
//do some stuff
//....
//write back to output
using(XmlTextWriter xml2 = new XmlTextWriter(outputFile, Encoding.UTF8) { Formatting = Formatting.Indented })
{
xDoc.CreateXmlDeclaration("1.0", null, "");
xDoc.Save(xml2);
}
inputfile contains this:
<?xml version="1.0" encoding="UTF-8" ?>
...
output.xml contains this:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
...

The standalone parameter should be null or String.empty.
xDoc.CreateXmlDeclaration("1.0", null, null);
Also CreateXmlDecleration just creates a declaration object. You still need to add it to the document, like this:
XmlDeclaration xDecl = xDoc.CreateXmlDeclaration("1.0", null, null);
if (xDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
xDoc.ReplaceChild(xDecl, xDoc.FirstChild);
else
xDoc.InsertBefore(xDecl, xDoc.DocumentElement);

Related

SqlXml removes XML header when comes from string

I'm developing a web app with C# and MVC4. Currently I'm working in converting string vars to SqlXml files. I have a XML file with this structure:
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/TimbreFiscalDigital/TimbreFiscalDigital.xsd" xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital" version="3.2" xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</cfdi:Comprobante>
I'm converting the above file to string successfully and then I'm usign the following code that converts a string to a SqlXML.
cfdiDocumento.CFDIXML = Serializar.XMLToSqlXml(comprobante);
Where cfdiDocumento.CFDIXML is a SqlXml var, Serializar.XMLToSqlXml(comprobante) method receives a string and executes the following code:
public static SqlXml XMLToSqlXml(string xmlString)
{
SqlXml sqlXmlFiltro = null;
if (xmlString != null)
{
StringReader sr = new StringReader(xmlString);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
XmlReader reader0 = XmlReader.Create(sr, settings);
sqlXmlFiltro = new SqlXml(reader0);
}
return sqlXmlFiltro;
}
When the code finishes successfully, the file is correct but is removing the xml header
<?xml version="1.0" encoding="utf-8"?>
The question is: How do I preserve the xml header when convierting to SqlXml var?
If you cannot change the type of your SqlXml attribute, you could try converting the SqlXml to xml document to append xml declaration and get the outer xml:
public string SqlXmlToString(SqlXml sqlXml)
{
XmlDocument doc = new XmlDocument();
doc.Load(sqlXml.CreateReader());
// Create XML declaration with your encoding.
XmlDeclaration xmldecl;
xmldecl = doc.CreateXmlDeclaration("1.0", null, null);
xmldecl.Encoding = "UTF-8";
// Add to the document the created declaration
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmldecl, root);
return doc.OuterXml;
}
Hope this is helpfully

xml data always being created as CDATA and not PCDATA

I wrote a web service with C# , and i want one of his methods to return an XML.
i've managed to do so , but all the data is being tagged as CDATA and not being parsed. its not what i am looking for.
this is my code :
[WebMethod(EnableSession = true, Description = "Returns the safe activities for the required days period in XML")]
public string GetSafeActivitiesXML(string safename, int days, string FileName)
{
string returnErrorCode = "001";
try
{
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
//IndentChars = " ",
//NewLineChars = "\n",
//NewLineHandling = NewLineHandling.None,
//Encoding = System.Text.Encoding.UTF8
};
StringWriter sb = new StringWriter();
XmlWriter writer = XmlWriter.Create(sb,settings);
writer.WriteStartDocument();
writer.WriteStartElement("GetSafeActivitiesResult", "");
int lineCouner = 0;
if (safeActivities.Count > 0)
{
writer.WriteStartElement("ListOfStrings", "");
foreach (ActivityLogRecord activity in safeActivities)
{
writer.WriteStartElement("string");
writer.WriteElementString("outFileName", (activity.Info1.Substring(activity.Info1.LastIndexOf("\\")+1)));
writer.WriteElementString("activityTmStamp", activity.Time.ToString());
writer.WriteElementString("userName", activity.UserName);
writer.WriteElementString("ActionID", activityCode);
writer.WriteElementString("direction", direction);
writer.WriteElementString("path", activity.Info1);
writer.WriteEndElement();
lineCouner++;
}
}
writer.WriteEndElement();
}
writer.WriteStartElement("retunCode");
writer.WriteString((lineCouner > 0) ? "0" : "2");
writer.WriteEndElement();
writer.WriteStartElement("retunMessage");
writer.WriteString((lineCouner > 0) ? "תקין" : "אין נתונים");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
XmlDocument xmlOut = new XmlDocument();
xmlOut.LoadXml(sb.ToString());
writer.Close();
//xmlOut.Save(xxx);
string finalOutput = sb.ToString();
finalOutput.Replace("![CDATA[", "").Replace("]]", "");
return sb.ToString();
}
catch (Exception ex)
{
this.LogWrite("GetSafeActivities", string.Format("Operation has failed: {0}, internal errorcode: {1}", ex.Message,returnErrorCode), Session.SessionID, true);
return string.Format("<ReturnCode>{0}</ReturnCode><ReturnMSG>{1}</ReturnMSG>", "שגוי", ex.Message) ;
}
}
This is an example for the current output:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetSafeActivitiesXMLResponse xmlns="http://www.securenet.co.il">
<GetSafeActivitiesXMLResult><![CDATA[<?xml version="1.0" encoding="utf-16"?>
<GetSafeActivitiesResult>
<ListOfStrings>
<string>
<outFileName>code-xmp-tmp.txt</outFileName>
<activityTmStamp>21/06/2015 10:58:38</activityTmStamp>
<userName>naaman</userName>
<ActionID>קובץ אוחסן בכספת</ActionID>
<direction>Unknown</direction>
<path>Root\fgdf\code-xmp-tmp.txt</path>
</string>
</ListOfStrings>
<retunCode>0</retunCode>
<retunMessage>תקין</retunMessage>
</GetSafeActivitiesResult>]]></GetSafeActivitiesXMLResult>
</GetSafeActivitiesXMLResponse>
</soap:Body>
This is what i want to achieve:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetSafeActivitiesXMLResponse xmlns="http://www.securenet.co.il">
<GetSafeActivitiesXMLResult><?xml version="1.0" encoding="utf-16"?>
<GetSafeActivitiesResult>
<ListOfStrings>
<string>
<outFileName>code-xmp-tmp.txt</outFileName>
<activityTmStamp>21/06/2015 10:58:38</activityTmStamp>
<userName>naaman</userName>
<ActionID>קובץ אוחסן בכספת</ActionID>
<direction>Unknown</direction>
<path>Root\fgdf\code-xmp-tmp.txt</path>
</string>
</ListOfStrings>
<retunCode>0</retunCode>
<retunMessage>תקין</retunMessage>
</GetSafeActivitiesResult></GetSafeActivitiesXMLResult>
</GetSafeActivitiesXMLResponse>
</soap:Body>
so my question really is , how to get rid of the CDATA tag, and why is it there on the first place.
i'm new to xml, so please be patient.
The output you want to achieve is XML that is not well-formed: you're essentially trying to nest an XML document, complete with an XML declaration (i.e. <?xml version="1.0" encoding="utf-16"?>), as literal character data within an XML document (or fragment) -- this is not a legal construct.
The proper way to include an XML document, or any text which would be recognized as markup, within another XML document (element) is to basically escape it by using a CDATA section so that it is not parsed as markup. And that is exactly what the web service/SOAP infrastructure is doing for you.
If it didn't do that and your XML text became parsed data (PCDATA) like you want, the consuming parser would throw an exception or return an error because your web service response XML would not be well-formed.
the method returned a String type, and that was the problem.
i changed the return type to XmlDocument, and now its all honey and nuts.

XML document processing cant load file

I am writing an application where i need to pull information out of a XML Document.
My XML document is stored in my projects bin/ Debug file.
I cant get it working.
XML document named informationData:
<xml>
<information>
<name >stian</name>
<surname>Kruger</surname>
<tel>0825514302</tel>
<photo>1234JLJ.jpg</photo>
</information>
</xml>
my call code:
private void btnReadXML_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("informationData.xml");
XmlNodeList dataNodes = xmlDoc.SelectNodes("/information");
foreach (XmlNode node in dataNodes)
{
Name = node.SelectSingleNode("name").InnerText;
Surname = node.SelectSingleNode("surname").InnerText;
TelNumber = Convert.ToInt32(node.SelectSingleNode("tel").InnerText);
}
}
Your XPath selector is wrong. Replace:
XmlNodeList dataNodes = xmlDoc.SelectNodes("/information");
with:
XmlNodeList dataNodes = xmlDoc.SelectNodes("//information");
or with:
XmlNodeList dataNodes = xmlDoc.DocumentElement.SelectNodes("information");
Also make sure that the XML file is present in the same folder as the running executable (you said bin/Debug/informationData.xml). If the XML file is part of your Visual Studio project you could select it and in the properties set Copy to Output Directory to Copy if newer. This way VS will automatically copy the XML file to this output folder everytime you compile the project.
You can use this code
<?xml version="1.0" encoding="utf-8" ?>
<information>
<name >stian</name>
<surname>Kruger</surname>
<tel>0825514302</tel>
<photo>1234JLJ.jpg</photo>
</information>
var xmlDoc = XDocument.Load("informationData.xml");
var name = xmlDoc.Element("name").Value;
var surname = xmlDoc.Element("surname").Value;
var telNumber = Convert.ToInt32(xmlDoc.Element("tel").Value);
add <?xml version="1.0" encoding="utf-8"?> as first line in XML file

Preserve xml formatting using XmlDocument

I am using XmlDocument to work with xml
How do I save my "XmlDocument" with my current formatting?
Current formatting:
<?xml version="1.0" encoding="utf-8"?>
<root>
<element></element>
</root>
Code:
XmlDocument testDoc = new XmlDocument();
testDoc.Load(#"C:\Test.xml");
**(do reading/writing using only XmlDocument methods)**
testDoc.Save(#"C:\Test.xml");
There is a similar topic:
XmlDocument class is removing formatting, c#, .NET
The accepted answer is PreserveWhiteSpace = true, which in reality removes all whitespaces instead of preserving them.
Example:
Code:
XmlDocument testDoc = new XmlDocument();
testDoc.Load(#"C:\Test.xml");
testDoc.PreserveWhitespace = true;
testDoc.Save(#"C:\Test.xml");
Result:
<?xml version="1.0" encoding="utf-8"?><root><element></element></root>
Setting PreserveWhitespace to true works for me - but you've got to do it before loading so that the whitespace doesn't get thrown away at load time:
using System;
using System.Xml;
class Test
{
static void Main()
{
XmlDocument testDoc = new XmlDocument();
testDoc.PreserveWhitespace = true;
testDoc.Load("Test.xml");
testDoc.Save("Output.xml");
}
}
I've just tried that, and the whitespace was preserved.
Umm. I'm seeing whitespace being preserved when using PreserveWhiteSpace=true. Perhaps it was false when you loaded?
var xmlStr = #"<?xml version=""1.0"" encoding=""utf-8""?>
<root>
<element></element>
</root>";
var xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(xmlStr);
xmlDoc.Save(Console.Out);
Shows:
<?xml version="1.0" encoding="utf-16"?>
<root>
<element></element>
</root>
use preservewhitespace before you load. It will keep formatting same
like above
var xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(xmlStr);
if you will use it after loading. it will kill white spaces in between

Add a Text line in xml on a particular location?

How can I insert the following stylesheet information into my existing xml file which is created using C#?
<?xml-stylesheet type="text/xsl" href="_fileName.xsl"?>
Or.... Can I add this line at the time of creation of the new XML file?
Edit:
I tried to achieve the above using XmlSerialier (hit and trial), something like this:
// assumes 'XML' file exists.
XmlDocument doc = new XmlDocument();
XElement dataElements = XElement.Load("_fileName.xml");
XmlSerializer xs = new XmlSerializer(typeof(Parents));
var ms = new MemoryStream();
xs.Serialize(ms, parents);
ms.Seek(0, SeekOrigin.Begin); // rewind stream to beginning
doc.Load(ms);
XmlProcessingInstruction pi;
string data = "type=\"text/xsl\" href=\"_fileName.xsl\"";
pi = doc.CreateProcessingInstruction("xml-stylesheet", data);
doc.InsertBefore(pi, doc.DocumentElement); // insert before root
doc.DocumentElement.Attributes.RemoveAll(); // remove namespaces
But the output xml is getting corrupted:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="_fileName.xsl"?>
<parents />
Whereas the desired output is something like:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="_fileName.xsl"?>
<parents>
<parent>
<Child1>
<child2>
</parent>
</parents>
Did this help to understand what's my problem???
You didn't answer the question.. "what lib do you use".
Although I advise:
XDocument
if you would use it you could do something like:
XDocument document = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
document.Add(new XProcessingInstruction(
"xml-stylesheet", "type=\"text/xsl\" href=\"_fileName.xsl\""));
//and then your actual document...
document.Add(
new XElement("parent",
new XElement("child1"),
new XElement("child2")
)
);
EDIT:
Ok So you could do it like:
XDocument document = XDocument.Load("file");
document.AddFirst(new XProcessingInstruction(
"xml-stylesheet", "type=\"text/xsl\" href=\"LogStyle.xsl\""));
Is this what you're looking for?

Categories

Resources