I am serializing an object like this:
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
(having created the nodes like this)
XmlElement newchild = doc.CreateElement(nodename);
newchild.InnerText = data;
targetnode.AppendChild(newchild);
if data!="" all is well and serializer returns:
<mynode>TheData</mynode>
If data=="" the serializer returns:
<mynode>
</mynode>
Where did that blank line come from?
I've tried the obvious like only setting newchild.InnerText=data when data is nonblank.
In XML both <mynode><\mynode> and <mynode>\n</mynode> are equivalent, so it should not matter, but you could modify the underlining XMLWriter to Serialize the output the way you want it.
Found a simple route
if (data.Length == 0) newchild.IsEmpty = true;
else newchild.InnerText = data;
hope this helps someone.
Related
I have to modify a incoming SOAP XML message to add a namespace to one of the elements so that the deserialisation will work. However when I add the xmlns attribute to the correct element, I get an error when I try to load the xml in to an XmlWriter via a stream (which I need to do to in my IClientMessageInspector implementation to replace the Message reply).
The prefix '' cannot be redefined from '' to 'http://www.example.com' within the same start element tag.
I have a work around, which is that after I've modifed the attribute, I reload the entire XML document from it's own OuterXML. This works for some reason, but makes me think there must be a 'correct' way to do this.
Here's a sample test that demonstrates the problem and my current solutions:
[Test]
public void XmlNamespaceTest()
{
var originalXmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><TestElement><Child>thing</Child></TestElement>";
var desiredXmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><TestElement xmlns=\"http://www.example.com\"><Child>thing</Child></TestElement>";
var doc = new XmlDocument();
doc.LoadXml(originalXmlString);
Assert.That(originalXmlString, Is.EqualTo(doc.OuterXml));
// Write this document via an XMLWriter
var ms = new MemoryStream();
var xmlWriter = XmlWriter.Create(ms);
doc.WriteTo(xmlWriter);
xmlWriter.Flush();
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
var originalXmlViaXmlWriter = sr.ReadToEnd();
Assert.That(originalXmlString, Is.EqualTo(originalXmlViaXmlWriter));
// Add the namespace to the element
((XmlElement)doc.GetElementsByTagName("TestElement").Item(0))?.SetAttribute("xmlns", "http://www.example.com");
Assert.That(desiredXmlString, Is.EqualTo(doc.OuterXml));
// Now attempt to write this modified xml via an XMLWriter
ms.SetLength(0);
xmlWriter = XmlWriter.Create(ms);
//Uncomment line below to fix the error.
//doc.LoadXml(doc.OuterXml);
doc.WriteTo(xmlWriter);
xmlWriter.Flush();
ms.Position = 0;
sr = new StreamReader(ms);
var modifedXmlViaXmlWriter = sr.ReadToEnd();
Assert.That(desiredXmlString, Is.EqualTo(modifedXmlViaXmlWriter));
}
According to this you can't change an elements namespace in an XmlDocument. This is also what #LocEngineer found in his comment. The referenced article mentions that the only way to do this is to save and reload the XmlDocument, which is exactly what you are doing.
If you are in a position to use XDoxument instead, it is possible. See this answer for a solution.
This question already has answers here:
Can we force XmlWriter to issue <my-tag></my-tag> rather than <my-tag/>?
(7 answers)
Closed 9 years ago.
I am trying below code to serialize an object. The problem is if some elements are null then they have self closing tags like below:
<City/> which I want to be like this <City> </City>. Any thoughts?
private string GetXMLFromObject(object o)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
MemoryStream ms = new MemoryStream();
XmlWriter writer = XmlWriter.Create(ms, settings);
XmlSerializerNamespaces names = new XmlSerializerNamespaces();
names.Add("", "");
XmlSerializer serializer = new XmlSerializer(o.GetType());
serializer.Serialize(writer, o, names);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
string xml = sr.ReadToEnd();
return xml;
}
With regards to validity, both <City/> and <City> </City> are valid and will be processed correctly by any XML Parser.
If you still want to force it, do as follows. What you are looking for is the WriteFullEndElement() method. See MSDN for more:
writer.WriteStartElement("City");
writer.WriteString(inputCity);
writer.WriteFullEndElement();
This will force it to serialize City as <City></City> when inputCity is empty.
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.
I am trying to write an XML response for my web service however I can't figure out how to make the declaration appear in the response.
My code is like so :
StringBuilder sBuilder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sBuilder))
{
writer.WriteStartDocument();
writer.WriteStartElement("ReportResponse");
Response.WriteXml(writer);
writer.WriteEndElement();
writer.WriteEndDocument();
}
var response = XElement.Parse(sBuilder.ToString());
return response;
Response is just a POCO for storing response data.
I am aware that the Save method includes the declaration and the ToString() method does not. I need to write my declaration back with ToString().
I really just want to return custom XML from my REST Service without casting my string 100 times to return valid XML. Is this even possible or am just spinning my wheels ?
If you want to include xml declaration, you can do it this way:
XDocument xdoc = XDocument.Parse(xmlString);
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
xdoc.Save(writer);
}
Console.WriteLine(builder);
Update:
I've noticed, that StringWriter spoils encoding. So one more option is to do so:
string docWithDeclaration = xdoc.Declaration + xdoc.ToString();
I have an XML file that I deserialize, the funny part is the XML file is the was serialized
using the following code:
enter code here
var serializer = new XmlSerializer(typeof(CommonMessage));
var writer = new StreamWriter("OutPut.txt");
serializer.Serialize(writer, commonMessage);
writer.Close();
And i m trying to deserialized it again to check if the output match the input.
anyhow here is my code to deserialize:
var serializer = new XmlSerializer(typeof(CommonMessage));
var reader = new StringReader(InputFileName);
CommonMessage commonMessage = (CommonMessage)serializer.Deserialize(reader);
Replace StringReader with StreamReader and it will work fine. StringReader reads value from the string (which is file name in your case).
I just had the same error message but different error source. In case someone has the same problem like me. I chopped off the very first char of my xml string by splitting strings. And the xml string got corrupted:
"?xml version="1.0" encoding="utf-16"?> ..." // my error
"<?xml version="1.0" encoding="utf-16"?> ..." // correct
(1,1) means basically first char of the first line is incorrect and the string can't be deserialized.
include in your CommonMessage class the XmlRoot element tag with your xmlroot eg:[XmlRoot("UIIVerificationResponse")]
You should disable the order mark in the StreamWriter constructor like this:
UTF8Encoding(false)
Full sample:
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(false)))
{
xmlSerializer.Serialize(writer, objectToSerialize, ns);
return Encoding.UTF8.GetString(stream.ToArray());
}