XmlTextWriter serialize Object to XML element - c#

I would like to perform object serialization to only one branch in an existing XML file. While reading by using:
RiskConfiguration AnObject;
XmlSerializer Xml_Serializer = new XmlSerializer(typeof(RiskConfiguration));
XmlTextReader XmlReader = new XmlTextReader(#"d:\Projects\RiskService\WCFRiskService\Web.config");
XmlReader.ReadToDescendant("RiskConfiguration");
try
{
AnObject = (RiskConfiguration)Xml_Serializer.Deserialize(XmlReader);
AnObject.Databases.Database[0].name = "NewName";
}
finally
{
XmlReader.Close();
}
It is possible, I do not know how to edit the object again performed it can save the file without erasing other existing elements in an XML file. Can anyone help me?
I found a way to display the desired item serialization. How do I go now instead of the paste to the original element in XML?
StringWriter wr = new StringWriter();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
settings.Encoding = System.Text.Encoding.Default;
using (XmlWriter writer = XmlWriter.Create(wr, settings))
{
XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
emptyNamespace.Add(String.Empty, String.Empty);
Xml_Serializer.Serialize(writer, AnObject, emptyNamespace);
MessageBox.Show(wr.ToString());
}

First of all, you should stop using new XmlTextReader(). That has been deprecated since .NET 2.0. Use XmlReader.Create() instead.
Second, XML is not a random-access medium. You can't move forward and backwards, writing into the middle of the file. It's a text-based file.
If you need to "modify" the file, then you'll need to write a new version of the file. You could read from the original file, up to the point where you need to deserialize, writing the nodes out to a new version of the file. You could then deserialize from the original file, modify the objects, and serialize out to the new version. You could then continue reading from the original and writing the nodes out to the new version.

Related

How can I save an XmlDocument without the XML Prolog?

While working on csproj files as xml files (xmlDocument) somehow after saving, encoding changes from UTF-8 to ASCII. The only solution I figured out is to use StreamWriter with declared encoding. But this adds a header to file.
Questions:
1. Do you know any other solution to this problem?
2. Can I leave changed csproj?
StreamReader sr = new StreamReader(projectFilePath, Encoding.UTF8);
XmlDocument xmlCsproj = new XmlDocument();
xmlCsproj.Load(sr);
sr.Close();
// Working on XML nodes (replace references paths)
StreamWriter sw= new StreamWriter(projectFilePath, false, Encoding.UTF8);
xmlCsproj.Save(sw);
sw.Close();
This should work?
var writer = new XmlTextWriter(projectFilePath, Encoding.UTF8)
{
Formatting = Formatting.Indented
};
xmlCsproj.WriteContentTo(writer);
writer.Close();
First of all, UTF8 character values are identical to US-ASCII values in the range 0-127. There's no way to say if a csproj file was saved as US-ASCII or UTF8 unless the file contained non-English text, like non-English file paths. Is that what happened here? Even so, XmlDocument.Save should have used UTF8 by default.
You can control how an XmlDocument is written to a stream or file using an XmlWriter and XmlWriterSettings. In this case, you need to set the OmitXmlDeclaration :
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
var writer = XmlWriter.Create(projectFilePath, settings);
xmlCsproj.Save(sw);
sw.Close();
The default encoding is UTF8. To change it, you can set the XmlWriterSettings.Encoding to a different value

How to write C# DataSet object to XML with customized nodes structure?

I have a similar case - I receive a DataSet object with data tables willed with data (e. g. customers table ...) from an external module (done by other programmer).
I then save the data set object to an xml using the writeXml method - here is my code
public void Save(string myXmlFilePath)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = System.Text.Encoding.UTF8;
settings.Indent = true;
settings.NewLineHandling = NewLineHandling.None;
using (XmlWriter writer = XmlWriter.Create(myXmlFilePath, settings))
{
ExportObject.WriteXml(writer);
writer.Close();
}
}
I get the standard xml file output structure like this:
<NewDataSet>
<Customers>...</Customers>
<Customers>...</Customers>
<NewDataSet>`
However I want the structure like this
<Customers>
<Customer>...</Customer>
<Customer>...</Customer>
</Customers>`
How can I achieve this?
Specify the desired names to the dataset and the tables within it.
ExportObject.DataSetName = "Customers";
ExportObject.Tables[0].TableName = "Customer";
A work around is to let WriteXml write however it likes and then do an XSD transform to the format you prefer.

XDocument automatically indents files on parse and does not remove indent on save

I am seeking a help regarding file saving of XML file using XDocument (NOT XMLDocument).
So I have a xml file that does not have indentation (in fact it is 1 line). When I read this to XDocument using XDocument.Parse (after reading and storing string using StreamReader), the resulting XDocument is indented.
Alright, I thought it will be fine as long as if I can save it back to the file without indentation. However, even though I have
XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.NewLineOnAttributes = false;
writerSettings.NewLineHandling = NewLineHandling.None;
writerSettings.Indent = false;
and pass that in when I create XmlWriter
using (var writer = XmlWriter.Create(u.ToFileSystemPath(), settings))
{
xd.Save(writer);
}
The resulting XML file still has indentation. When I am debugging on Visual studio, I noticed that the writer is a class XmlWellFormedWriter. Does this have something to do with my result? Any help would be appreciated.
Thank you.
SaveOptions are available on Save() as well as ToString().
string xmlstring =
#"<Top>
<First>1</First>
<Second>Dude</Second>
<Third>Now</Third>
</Top>";
XDocument doc = XDocument.Parse(xmlstring);
doc.Save(#"C:\temp\noIndet.xml", SaveOptions.DisableFormatting);
// string noIndent = doc.ToString(SaveOptions.DisableFormatting);
Output:

Creating an XML with multiple root elements

I'm trying to create an XML with multiple root elements. I can't change that because that is the way I'm supposed to send the XML to the server. This is the error I get when I try to run the code:
System.InvalidOperationException: This operation would create an incorrectly structured document.
Is there a way to overwrite this error and have it so that it ignores this?
Alright so let me explain this better:
Here is what I have
XmlDocument doc = new XmlDocument();
doc.LoadXml(_application_data);
Now that creates the XML document and I can add a fake root element to it so that it works. However, I need to get rid of that and convert it into a DocumentElement object.
How would I go about doing that?
Specify Fragment when creating XmlWriter as shown here
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.CloseOutput = false;
// Create the XmlWriter object and write some content.
MemoryStream strm = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(strm, settings))
{
writer.WriteElementString("orderID", "1-456-ab");
writer.WriteElementString("orderID", "2-36-00a");
writer.Flush();
}
If it has multiple root elements, it's not XML. If it resembles XML in other ways, you could place everything under a root element, then when you send the string to the server, you just combine the serialized child elements of this root element, or as #Austin points out, use an inner XML method if available.
just create an XML with single root then get it's content as XML text.
you are talking about XML fragment anyways, since good xml has only one root.
this is sample to help you started:
var xml = new XmlDocument();
var root = xml.CreateElement("root");
root.AppendChild(xml.CreateElement("a"));
root.AppendChild(xml.CreateElement("b"));
Console.WriteLine(root.InnerXml); // outputs "<a /><b />"

Why are all of my line-breaks changing from "/r/n" to "/n/" and how can I stop this from happening?

I am saving my files as xml documents, using XDocument.Save(path), and after saving and loading a document all of the line breaks have changed from "/r/n" to "/n/". Why is this happening and how can I fix it?
You can use XmlWriterSettings to control what your line-break characters are:
XmlWriterSettings xws = new XmlWriterSettings();
xws.NewLineChars = "\r\n";
using (XmlWriter xw = XmlWriter.Create("whatever.xml", xws))
{
xmlDocumentInstance.Save(xw);
}
Whatever you're using to read in your XML might be normalizing your line endings.
If you set the PreserveWhiteSpace property on your XmlDocument object before calling Load() and Save() then this will not happen:
var doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("foo.xml");
...
doc.Save("bar.xml"); // Line endings will not be altered

Categories

Resources