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
Related
I have a XML structer like that
<?xml version="1.0" encoding="utf-8"?>
<Product>
<ProductName>da</ProductName>
<PluginPath></PluginPath>
<Instances></Instances>
</Product>
and i serialize my object to string.
<?xml version="1.0"?>
<Instance xmlns:xsi="http://bla bla" xmlns:xsd="bla bla" UniqueId="d4820029b7d7">
<InstanceName>Instance MyTestPluginForm</InstanceName>
<Description>Test Plugin IW</Description>
<AddedDate>2016-10-19T11:05:10.7443404+02:00</AddedDate>
<LogSettings>
<LoggingLevel>None</LoggingLevel>
<LogFilePath /><MaximumSize>100</MaximumSize
<ClearAfterDays>7</ClearAfterDays>
<IsSaveActiviesToEventLog>false</IsSaveActiviesToEventLog>
</LogSettings>
<ProductSpecific/>
</Instance>
So I want to append the second one in the Instances node in the first xml. But as you see both has xml definition on the top and after serializazion i got xmlns:xsi and xmlns:xsd attributes.
How to solve this problem?
PS: I do not want to create XML elements. Because my xml schema is dynamic. It has to be done with serialization. (I already checked this sample)
I solved the problem. using the code here
public static void CreateXmlFile(Instance instance, string filePath)
{
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Product><ProductName>da</ProductName><PluginPath></PluginPath><Instances></Instances></Product>";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
xmlDocument.Save(filePath);
XmlNode xnode = xmlDocument.CreateNode(XmlNodeType.Element, "Instances", null);
XmlSerializer xSeriz = new XmlSerializer(typeof(Instance));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlWriterSettings writtersetting = new XmlWriterSettings();
writtersetting.OmitXmlDeclaration = true;
StringWriter stringwriter = new StringWriter();
using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(stringwriter, writtersetting))
{
xSeriz.Serialize(xmlwriter, instance, ns);
}
xnode.InnerXml = stringwriter.ToString();
XmlNode bindxnode = xnode.SelectSingleNode("Instance");
xmlDocument.DocumentElement.SelectSingleNode("Instances").AppendChild(bindxnode);
xmlDocument.Save(filePath);
}
I am writing a XML using XmlDocument, I need a element or attribute like shown below
The element or attribute required is <?Validversion="1" ?>
how to create using xmldocument or xmlwriter.
// to create <?Validversion="1" ?>
XmlDocument aDoc = new XmlDocument();
aDoc.CreateXmlDeclaration("1.0", "utf-16", null);
XmlCDataSection aDataSec =aDoc.CreateCDataSection("?Version = 2");
aDoc.AppendChild(aDataSec);
aDoc.Save("c:\\vector.xml");
You are looking for XmlDocument.CreateProcessingInstruction and not CDATA section:
var document = new XmlDocument();
document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-16", null));
var piNode = document.CreateProcessingInstruction("Version", "=\"2\"");
document.AppendChild(pi);
Side note: don't forget to AppendChild newly created node.
I have this string :
<test>I am a test</test>
But when I write it in my xml file, and open it, I have this :
<test>I am a test</test>
I don't know how to use the good formatting. I tried HttpUtility.HtmlDecode, but it does not solve my problem.
Do you have an idea on this ?
Edit : Sorry for not having posted my code before, I thought my problem was really really trivial. Here is a sample I just wrote that resumes the situation (I'm not at work anymore so I don't have the original code) :
XmlDocument xmlDoc = new XmlDocument();
doc.LoadXml("<root>" +
"<test>I am a test</test>" +
"</root>");
string content = xmlDoc.DocumentElement.FirstChild.InnerXml;
XDocument saveFile = new XDocument();
saveFile = new XDocument(new XElement("settings", content));
saveFile.Save("myFile.xml");
I just want my xml file content looks like my original string,
so in my case the file would normally contain :
<settings>
<root>
<test>I am a test</test>
</root>
</settings>
Right ? But instead, I have something like :
<settings><root><test>I am a test</test></root>
</settings>
You can do something along the lines of Converting XDocument to XmlDocument and vice versa to convert the root element of your XmlDocument to an XElement and then add it to your XDocument:
public static class XmlDocumentExtensions
{
public static XElement ToXElement(this XmlDocument xmlDocument)
{
if (xmlDocument == null)
throw new ArgumentNullException("xmlDocument");
if (xmlDocument.DocumentElement == null)
return null;
using (var nodeReader = new XmlNodeReader(xmlDocument.DocumentElement))
{
return XElement.Load(nodeReader);
}
}
}
And then use as follows:
// Get legacy XmlDocument
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<root>" +
"<test>I am a test</test>" +
"</root>");
// Add its root element to the XDocument
XDocument saveFile = new XDocument(
new XElement("settings", xmlDoc.ToXElement()));
// Save
Debug.WriteLine(saveFile.ToString());
And the output is:
<settings>
<root>
<test>I am a test</test>
</root>
</settings>
Note this avoids the overhead of converting the XmlDocument to an XML string and re-parsing it from scratch.
I need to add the following code to the beginning of an XML file, while creating it:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="colors.xslt"?>
I'm sure there is a method for this, but I haven't found it yet. I'm using C#.
Thank you
XmlDocument.CreateProcessingInstruction Method
public static void Main()
{
var doc = new XmlDocument();
doc.AppendChild(doc.CreateProcessingInstruction(
"xml-stylesheet",
"type='text/xsl' href='colors.xslt'"));
}
For LINQ XDocument you can use this:
XDocument xDoc = new XDocument();
xDoc.Add(new XProcessingInstruction("xml-stylesheet",
"type=\"text/xsl\" href=\"xml-style.xslt\""));
I have an XmlDocument that is from a webservice, and I want to use a subset of the xml to populate a Gridview control. Unfortunately, it contains extra data that I don't need. So I want to create a new XmlDocument from a subset of the existing xml document.
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xmlDoc = Object.ReturnsXmlDocument;
XmlDocument xmlDocResults = ??? //<results><result></result></results>
}
Basically, I want to create a new XmlDocument with the as the root element. Below is a shortened example of the original xml doc:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<query_time>.12</query_time>
<number_results>3</number_results>
<results>
<result><id>1</id></result>
<result><id>2</id></result>
<result><id>3</id> </result>
</results>
</xml>
Anthony's code helped point me in the right direction, but this is what actually worked for me.
XmlDocument xmlResults = new XmlDocument();
XmlDeclaration xmlDec = xmlResults.CreateXmlDeclaration("1.0", "utf-8", null);
XmlElement rootNode = xmlResults.CreateElement("results");
xmlResults.InsertBefore(xmlDec, xmlResults.DocumentElement);
xmlResults.AppendChild(rootNode);
XmlNode node = xmlDoc.GetElementsByTagName("results")[0];
xmlResults.GetElementsByTagName("results")[0].InnerXml = node.InnerXml.ToString();
What you need is ImportNode:-
XmlDocument xmlDoc = Object.ReturnsXmlDocument;
XmlDocument xmlResults = new XmlDocument();
xmlResults.AppendNode(xmlResults.ImportNode(xmlDoc.SelectSingleNode("/xml/results"));
Untested, but this should be pretty darn close:
XPathDocument original = new XPathDocument("original.xml");
XPathNavigator navigator = original.CreateNavigator();
navigator.MoveToChild("results", "");
XmlWriter results = XmlWriter.Create("results.xml");
navigator.WriteSubtree(results);
results.Close();
And then you can do whatever you need to with the XmlWriter - I'm not sure if you're trying to create the results XmlDocument on disk or not.