Indenting Xml file edited with XDocument in C# - c#

I have some code that edits and Xml file.
When I save the file the new elements are not properly indented while existing elements are, e.g.:
Before:
<MyGroup>
<ExistingElement1>a value</ExistingElement1>
<ExistingElement2>something else</ExistingElement2>
</MyGroup>
After:
<MyGroup>
<ExistingElement1>a value</ExistingElement1>
<ExistingElement2>something else</ExistingElement2>
<NewElement>Inserted by code</NewElement></MyGroup>
New elements are added with XElement, like:
myGroup.Add(new XElement(ns + "NewElement", "Inserted by code"));
when saving the file I use XmlWriterSettings as I want to avoid saving the XmlDeclaration:
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Encoding = Encoding.UTF8,
Indent = true
};
using (var writer = XmlWriter.Create(filePath, settings))
{
xmlDoc.Save(writer);
}
So it looks like that the Indent = true option is not working for the newly added elements, does anyone know why?
BTW, when I open the file I use LoadOptions.PreserveWhitespace
XDocument xmlDoc = XDocument.Load(filePath, LoadOptions.PreserveWhitespace);

Related

converting xmlDocument object data to pdf

XmlDocument doc = new XmlDocument();
string a=textBox1.Text;
doc.LoadXml(a.Substring(a.IndexOf(Environment.NewLine)));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("data.xml", settings);
doc.Save(writer);
In the above code converts textbox content to xml file.Now I required to process each element of the xmlDocument object(doc) and need to create pdf.
string in my textbox is like
Hello
and my Xml file data.xml is saved in debug folder of the project
now my pdf should contain a table with one row and one cell which contains "Hello" in it.
Could Any one help me to do this.I am very New to programming.
This is a rather vague question, I don't know what kind of content the "data.xml" can have and how it should be mapped to a PDF file.
You mentioned "Hello" as an example, but that cannot be loaded as XmlDocument...
Nevertheless, here is a small sample that will hopefully get you started (for creating a PDF file I used GemBox.Document):
string a = #"
<table>
<row>
<cell>Hello 1-1</cell>
<cell>Hello 1-2</cell>
</row>
<row>
<cell>Hello 2-1</cell>
<cell>Hello 2-2</cell>
</row>
</table>";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(a.Substring(a.IndexOf(Environment.NewLine)));
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
XmlWriter writer = XmlWriter.Create("data.xml", settings);
xmlDocument.Save(writer);
ComponentInfo.SetLicense("FREE-LIMITED-KEY");
DocumentModel pdfDocument = new DocumentModel();
Table table = new Table(pdfDocument);
table.TableFormat.PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage);
pdfDocument.Sections.Add(new Section(pdfDocument, table));
foreach (XmlNode xmlRow in xmlDocument.SelectNodes("/table/row"))
{
TableRow row = new TableRow(pdfDocument);
table.Rows.Add(row);
foreach (XmlNode xmlCell in xmlRow.SelectNodes(".//cell"))
row.Cells.Add(
new TableCell(pdfDocument,
new Paragraph(pdfDocument, xmlCell.InnerText)));
}
pdfDocument.Save("sample.pdf");
Also here is the resulting "sample.pdf":

XML Parsing Error: no element found message and empty document creation

I'm trying to create an xml file. I already set the document and have a result with Xmlwriter when printing to console but when it comes to having an actual .xml file on my desktop I always end up with empty files. Clearly I'm missing something or forgetting something but can't tell on my own.
Below is the piece of my code where it all happens (not).
public void button1_Click(object sender, EventArgs e)
{
XmlDocument dddxml = new XmlDocument();
//XmlDeclaration xmldecl;
//xmldecl = dddxml.CreateXmlDeclaration("1.0", null, null);
//xmldecl.Encoding = "UTF-8";
//xmldecl.Standalone = "yes";
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
StringBuilder builder = new StringBuilder();
writer = XmlWriter.Create(builder, settings);
writer.WriteStartDocument();
writer.WriteStartElement("root");
BlockSelect(0);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
Console.WriteLine(builder.ToString());
writer = XmlWriter.Create("DddXml.Xml", settings);
dddxml.Save(writer);
File.Create(path);//declared elsewhere, valid file location string
}
You have created new XmlDocument here:
XmlDocument dddxml = new XmlDocument();
But you haven't populated it in the rest of the code and in fact you're not using it and writing xml to string builder using WriteStartDocument and WriteEndElement methods of XmlWriter.
Thus your dddxml remains empty, so when you're trying to save it like this:
dddxml.Save(writer);
, there is nothing to save and you're getting empty file.
So you have to choose - will you use XmlDocument or XmlWriter to create and save your xml.
As commented by #Charles Mager, File.Create() just makes an empty file.
You can try to write directly to the file instead of using StringBuilder. Here's a sample to directly write to the file using the XmlWriter:
XmlWriter writer = XmlWriter.Create("C:\\ddxml.xml", settings);
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
See that the file is written on C:\ddxml.xml.
If you want you can also use LINQ, it's easier :
XDocument doc = new XDocument();
XNamespace ns = "";
doc.Add(new XElement(ns + "root"));
doc.Save(#"C:\DddXml.Xml");

XML Extra free space

Good day, in general is a problem, I work with XML through C# XMLdocument, after saving that "document", there is such a thing: 
<Name></Name>
After saving:
<Name>
</Name>
How to remove extra spaces?  I've tried: doc.PreserveWhitespace=true;  before saving and before loading. The result is not one that removes all spaces. XML document (large volume) become visually unreadable.
I have already tried, same result. And need Encoding windows-1251 Why XmlDocument do this bad thing? That free or whitespace important for me and my "program".
the problem is solved. thank you all
It can be done. You've got to help control the formatting options when you save the document:
XmlDocument doc = new XmlDocument();
using (var wr = new XmlTextWriter(fileName))
{
wr.Formatting = Formatting.None;
doc.Save(wr);
}
Or you can fine-tune it further with XmlWriterSettings:
var settings = new XmlWriterSettings
{
Indent = false,
NewLineChars = String.Empty
};
using (var wr = XmlWriter.Create(fileName, settings))
{
wr.Formatting = Formatting.None;
doc.Save(wr);
}

How to create a XML with a Specific Encoding using XSLT and XMLWRITER

I am trying to apply a XSL style sheet on a source xml and write the output to a target xml file. The xsl removes the xml comments present inside the source xml.
The target xml file has UTF-16 encoding in the header.
But still i want the output xml to be utf-8 encoding. The code i used is
XmlWriterSettings xwrSettings = new XmlWriterSettings();
**xwrSettings.Encoding = Encoding.UTF8;**
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("sample.xsl");
StringBuilder sb = new StringBuilder();
XmlReader xReader = XmlReader.Create("Source.xml");
XmlWriter xWriter = XmlWriter.Create(sb, xwrSettings);
xslt.Transform(xReader, xWriter);
File.WriteAllText("Target.xml",sb.ToString());
I tried to set the xml writer setting to be of UTF-8 but it is not working.
Since you are writing to file, why not just use:
using (XmlReader xReader = XmlReader.Create("Source.xml"))
using (XmlWriter xWriter = XmlWriter.Create("Target.xml", xwrSettings)) {
xslt.Transform(xReader, xWriter);
}
// your file is now written

Saving an xml file without

How do I work with an xml file that when updating it, after saving the commented lines would still be present.
Here's my code snippet for saving the file:
public static void WriteSettings(Settings settings, string path)
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
TextWriter writer = new StreamWriter(path);
serializer.Serialize(writer, settings);
writer.Close();
}
I'm not sure I understand you requirement. I would say don't use XmlSerializer because that's designed for creating serialized versions of objects in XML form. Objects don't have XML comments in them, so the XML generated for the object won't generate any comments. If you want to deal with pure XML, just use a simple XML parsing class, rather than one designed for serializing classes as XML documents:
string myXml =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine +
"<!-- This is a comment -->" + Environment.NewLine +
"<Root><Data>Test</Data></Root>";
System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
xml.PreserveWhitespace = true;
xml.LoadXml(myXml);
var newElem = xml.CreateElement("Data");
newElem.InnerText = "Test 2";
xml.SelectSingleNode("/Root").AppendChild(newElem);
System.Xml.XmlWriterSettings xws = new System.Xml.XmlWriterSettings();
xws.Indent = true;
using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(Console.Out, xws))
{
xml.WriteTo(xw);
}
This code will overwrite xml file completely. In order to keep comments in existing file you have to read it first, then update and save.

Categories