How I am creating an xml string of proper xml with the code below..
string myInputXmlString = #"<ApplicationData>
<something>else</something>
</ApplicationData>";
var doc = new XmlDocument();
doc.LoadXml(myInputXmlString);
XmlAttribute newAttr = doc.CreateAttribute(
"xsi",
"noNamespaceSchemaLocation",
"http://www.w3.org/2001/XMLSchema-instance");
doc.DocumentElement.Attributes.Append(newAttr);
var ms = new MemoryStream();
XmlWriterSettings ws = new XmlWriterSettings
{
OmitXmlDeclaration = false,
ConformanceLevel = ConformanceLevel.Document,
Encoding = UTF8Encoding.UTF8
};
var tx = XmlWriter.Create(ms, ws);
doc.Save(tx);
tx.Flush();
var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine(xmlString);
How do I add the xsd information to this so the xml looks like this (with "FullModeDataset.xsd" includded?
<ApplicationData
xsi:noNamespaceSchemaLocation="FullModeDataset.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
Instead of this which the current code is outputing
<ApplicationData
xsi:noNamespaceSchemaLocation=""
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
Does this work by chance?
doc.DocumentElement.SetAttribute("noNamespaceSchemaLocation",
"http://www.w3.org/2001/XMLSchema-instance",
"FullModeDataset.xsd");
Related
I'm using this method to generate an XML :
using (MemoryStream msRes = new MemoryStream())
using (StreamWriter objStreamWriter = new StreamWriter(msRes))
using (XmlWriter xw = XmlWriter.Create(objStreamWriter, new XmlWriterSettings() { Indent = true, IndentChars = String.Empty }))
{
XmlSerializer serializer = new XmlSerializer(doc.GetType());
serializer.Serialize(xw, doc);
return msRes.ToArray();
}
The result is that I have this sort of line <Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:iso:std:iso:20022:tech:xsd:camt.054.001.02">.
I'd like to remove the attribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" but keep xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:iso:std:iso:20022:tech:xsd:camt.054.001.02".
How can I do that ?
Thanks for your help !
You could try the below code to remove the xmlns entries:
var ns = new XmlSerializerNamespaces(); ns.Add("", "");
I have to create an xml file which has encoding as
<?xml version="1.0" encoding="ISO-8859-1"?>
Currently the xml I am creating using LINQ is having tag as
<?xml version="1.0" encoding="UTF-8"?>
how can I do this using LINQ only.
You should use XDeclaration:
var d = new XDocument(new XDeclaration("1.0", "ISO-8859-1", ""), new XElement("Root",
new XElement("Child1", "data1"),
new XElement("Child2", "data2")
));
You can save the XDocument to a StreamWriter having the desired encoding:
var xDocument = new XDocument(new XElement("root"));
var encoding = Encoding.GetEncoding("iso-8859-1");
using (var fileStream = File.Create("... file name ..."))
using (var streamWriter = new StreamWriter(fileStream, encoding))
xDocument.Save(streamWriter);
If you are using XMLDcoument, then you can do so like below:
XmlDocument doc = new XmlDocument();
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null);
doc.AppendChild(declaration);
var node = doc.CreateNode(XmlNodeType.Element, "Root", "");
doc.AppendChild(node);
doc.Save("TestDoc.xml");
I want to add
xsi:noNamespaceSchemaLocation="FullModeDataset.xsd"
and
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
as attibutes to my root node "ApplicationData" so the root node will look like this..
<ApplicationData
xsi:noNamespaceSchemaLocation="FullModeDataset.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />
I am creating the xml from a string, outputing a string that is proper xml with this code..
var doc = new XmlDocument();
doc.LoadXml(myInputXmlString);
var ms = new MemoryStream();
var tx = XmlWriter.Create(ms,
new XmlWriterSettings
{
OmitXmlDeclaration = false,
ConformanceLevel = ConformanceLevel.Document,
Encoding = UTF8Encoding.UTF8
});
doc.Save(tx);
//I TRIED THE COMMENTED CODE BELOW BUT WITH NO SUCCESS
//XmlAttribute newAttr = doc.CreateAttribute("xsi:noNamespaceSchemaLocation");
//newAttr.Value = "FullModeDataset.xsd";
//XmlElement applicationNode = doc.DocumentElement["AppicationData"];
//applicationNode.Attributes.Append(newAttr);
//doc.Save(tx);
var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());
how do I add these attributes to my xml string?
You need to create the attribute using the overload which takes the prefix and the namespace URL of the attribute you want to create, as shown below:
public class StackOverflow_14128649
{
public static void Test()
{
string myInputXmlString = #"<ApplicationData>
<something>else</something>
</ApplicationData>";
var doc = new XmlDocument();
doc.LoadXml(myInputXmlString);
XmlAttribute newAttr = doc.CreateAttribute(
"xsi",
"noNamespaceSchemaLocation",
"http://www.w3.org/2001/XMLSchema-instance");
newAttr.Value = "FullModeDataset.xsd";
doc.DocumentElement.Attributes.Append(newAttr);
var ms = new MemoryStream();
XmlWriterSettings ws = new XmlWriterSettings
{
OmitXmlDeclaration = false,
ConformanceLevel = ConformanceLevel.Document,
Encoding = UTF8Encoding.UTF8
};
var tx = XmlWriter.Create(ms, ws);
doc.Save(tx);
tx.Flush();
var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());
Console.WriteLine(xmlString);
}
}
i have a xml document that contains entity. when i load it and process and save then all entity get converted into UTF encoding. how to get document same as input content.
Input xml is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE chapter SYSTEM "DTD_v1.5\PLI.dtd">
<chapter num="1" update-date="November 2012" type="chapter">
<page num="3"/>
<title>Artist-Dealer Relations</title>
<para align="left"><content-style font-style="bold">S</content-style>i Salander-O’Reilly .</para>
<para>Since that time, the New York state artist consignment statute—which, </para>
<para>The of the artist’s work; the amount o and the like. </para>
<para>But firss of “dealer” and “gallery” interchangeably.</para>
<itemizedlist type="•">
<item><para>To care </para></item>
</itemizedlist>
<chapter>
I want out put also same as the above xml
i have try the following codes
XmlDocument xDoc = new XmlDocument();
string text = string.Empty;
text = ReadFile("38149_Chapter01_Art_Law_XML.xml", enmReadType.None, Encoding.Default);
xDoc.LoadXml(text);
xDoc.Save("38149_Chapter01_Art_Law_XML.xml");
and
string sXmlData = File.ReadAllText("38149_Chapter01_Art_Law_XML.xml", Encoding.Default);
xDoc.LoadXml(sXmlData);
XmlAttribute aa = xDoc.CreateAttribute("Name");
aa.Value = "Sarvesh";
XmlNode snode = xDoc.SelectSingleNode("//chapter");
snode.Attributes.Append(aa);
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.GetEncoding("ISO-8859-1");
XmlWriter xw = XmlWriter.Create(ms, settings);
xDoc.Save(xw);
xw.Close();
using (TextWriter tx = new StreamWriter("38149_Chapter01_Art_Law_XML.xml", false, Encoding.Default))
{
tx.Write(Encoding.UTF8.GetString(ms.ToArray()));
tx.Close();
}
}
I need to set the OmitXmlDeclaration property of the XmlWriterSettings for a XmlWriter to false to not have XML declarations created. The issue is that I have created the XmlWriter from a call of a XPathNavigator.AppendChild() method. Code below:
public String GetEntityXml<T>(List<T> entities)
{
XmlDocument xmlDoc = new XmlDocument();
XPathNavigator nav = xmlDoc.CreateNavigator();
using (XmlWriter writer = nav.AppendChild())
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(typeof(T).Name + "_LIST"));
ser.Serialize(writer, entities);
}
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
xmlDoc.WriteTo(xmlTextWriter);
string resultString = stringWriter.ToString();
stringWriter.Close();
xmlTextWriter.Close();
return resultString;
}
Any idea how to serialize the List and not have XML declarations?
I’m not getting the XML declaration when I execute your code. Serializing a List<int> gives me:
<Int32_LIST xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<int>5</int>
<int>7</int>
<int>2</int>
</Int32_LIST>
Note that the “XML declaration” that OmitXmlDeclaration refers to is typically something similar to:
<?xml version="1.0" encoding="UTF-8" ?>
If you’re instead referring to the xmlns parts, then those are called “XML namespace declarations”, and may be eliminated by initializing an XmlSerializerNamespaces instance with a default empty namespace, and passing it to your Serialize method:
XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(typeof(T).Name + "_LIST"));
var namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
ser.Serialize(writer, entities, namespaces);
The below is a shortened implementation which achieves the same result as your code:
public String GetEntityXml<T>(List<T> entities)
{
var sb = new StringBuilder();
var settings = new XmlWriterSettings { OmitXmlDeclaration = true };
using (XmlWriter writer = XmlWriter.Create(sb, settings))
{
XmlSerializer ser = new XmlSerializer(typeof(List<T>), new XmlRootAttribute(typeof(T).Name + "_LIST"));
var namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
ser.Serialize(writer, entities, namespaces);
}
return sb.ToString();
}
Try this approach (switched to var for readability):
public String GetEntityXml<T>(List<T> entities)
{
var xmlDoc = new XmlDocument();
var nav = xmlDoc.CreateNavigator();
using (var sw = new StringWriter())
{
//Create an XmlWriter that will omit xml declarations
var s = new XmlWriterSettings{ OmitXmlDeclaration = true };
using (var xmlWriter = XmlWriter.Create(sw, s))
{
//Use the following to serialize without namespaces
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
var ser = new XmlSerializer(typeof(List<T>),
new XmlRootAttribute(typeof(T).Name + "_LIST"));
ser.Serialize(xmlWriter, entities, ns);
}
//Pass xml string to nav.AppendChild()
nav.AppendChild(sw.ToString());
}
using (var stringWriter = new StringWriter())
{
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
xmlDoc.WriteTo(xmlTextWriter);
}
return stringWriter.ToString();
}
}
Rather than using nav.AppendChild() to create the XmlWriter, you can create the XmlWriter separately and then just use nav.AppendChild(string) to write the XML into xmlDoc. When you create the XmlWriter yourself, you can omit the XML declaration. Also, when you serialize, you'll probably want to omit the xmlns:xsi and xmlns:xsd namespaces using the XmlSerializerNamespaces class.