How to write CData in xml - c#

i have an xml like :
<?xml version="1.0" encoding="UTF-8"?>
<entry>
<entry_id></entry_id>
<entry_status></entry_status>
</entry>
i am writing data in it like:
XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status");
xnode.InnerText = "<![CDATA[ " + Convert.ToString(sqlReader["story_status"]) + " ]]>" ;
but its change "<" to "&lt" of CDATA.
Please tell me how to fill values in above xml as a CData format.
i know that we can create CDATA like :
XmlNode itemDescription = doc.CreateElement("description");
XmlCDataSection cdata = doc.CreateCDataSection("<P>hello world</P>");
itemDescription.AppendChild(cdata);
item.AppendChild(itemDescription);
but my process is to read node of xml and change its value not to append in it.
Thanks

As described here: msdn
// Create an XmlCDataSection from your document
var cdata = xdoc.CreateCDataSection(Convert.ToString(sqlReader["story_status"]));
// Append the cdata section to your node
xnode.AppendChild(cdata);

Do you really need it to be in CDATA, or do you just want to get the text in there in a way which won't require extra escaping in your code?
InnerText performs whatever escaping is required, so generally I'd just use
xnode.InnerText = Convert.ToString(sqlReader["story_status"]);
... but if you really want a CDATA node, you can create one yourself as per Nekresh's answer.

If you really need a CDATA section (see Jon's answer), you can achieve that like so:
XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status");
XmlCDataSection cdata = xdoc.CreateCDataSection(Convert.ToString(sqlReader["story_status"]));
xnode.InnerXml = cdata.OuterXml;
This will replace the contents of xnode, not append to it.

Use Node.InnerXml, not Node.InnerText. Node.InnerText is automatically replacing special values. Note that if you specify with CDATA in InnerXml, then Node.InnerText is text in CDATA.
Example:
public class Test
{
public static int Main(string[] args)
{
const string xmlTxt = #"<?xml version=""1.0"" encoding=""UTF-8""?>
<entry>
<entry_id></entry_id>
<entry_status></entry_status>
</entry>";
TextReader treader = new StringReader(xmlTxt);
XmlReader xreader = XmlReader.Create(treader);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(xreader);
XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status");
//xnode.InnerText = "<![CDATA[something]]>";
xnode.InnerXml = "<![CDATA[something]]>";
Console.WriteLine("inner text is: " + xnode.InnerText);
xdoc.Save(Console.Out); Console.WriteLine();
return 0;
}
}
Program's output:
inner text is: something
<?xml version="1.0" encoding="ibm852"?>
<entry>
<entry_id>
</entry_id>
<entry_status><![CDATA[something]]></entry_status>
</entry>

XmlNode childNode = node.ChildNodes[0];
if (childNode is XmlCDataSection)
{
XmlCDataSection cdataSection = childNode as XmlCDataSection;
cdataSection.Value = newValue;
}

You can use writer.WriteCData(value);
where writer is XmlWriter object.

Related

Reading XML file results in index out of range exception

Using C# I have an XML file like
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account>
<name>Jani</name>
</Account>
</root>
and I also have a function to read the name node as:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("lib//user.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
label1.Text = name.ToString();
but I am getting index out of range error as:
Why is this happening?
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
node is your root node. Which looks like this:
<root>
How many attributes does it have? None, as it turns out. An attribute in XML is one of these bar="baz" things:
<foo bar="baz">
node.Attributes[0] refers to the first attribute. There is no first attribute, there's no second attribute -- you didn't use attributes in this XML at all. Hence, that's out of range. There's no first item in an empty collection.
What you want is an element named name, which is farther down inside your XML tree.
Probably this:
var node = xmlDoc.DocumentElement.SelectSingleNode("/root/Account/name");
And then you'll want to look at node.InnerText to get "Jani" out of it.
You are trying to read node.Attributes[0].Value but there is no attribtues in your sample XML file. Not sure of the exact syntax but it should probably be closer to node.Value
As mentioned by other answers, your current XML does not have attributes.
private void DoIt()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
//string name = node.Attributes[0].Value;
string name = node["Account"].InnerText;
}
If your XML did have attributes
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account name="Jani" />
</root>
Then you could do this:
private void DoItAgain()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data2.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node["Account"].Attributes[0].Value;
}

C# how to create a custom xml document

I'm really just trying to create a custom xml document for simple configuration processing.
XmlDocument xDoc = new XmlDocument();
string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie"};
foreach (string node in NodeArray)
{
XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element,node.Split('|')[0],null);
//xmlNode.Value = node.Split('|')[0];
xmlNode.InnerText = node.Split('|')[1];
xDoc.DocumentElement.AppendChild(xmlNode);
}
What i'm trying to get is this.
<?xml version="1.0" encoding="ISO-8859-1"?>
<Fruits>Fruit</Fruits>
<Vegetables>Veggie</Vegetables>
i get not set to value of an object at xDoc.DocumentElement.AppendChild(xmlNode);
Unfortunately, You can't make that XML structure.
All XML documents must have a single root node. You can't have more.
Try something like this
XmlDocument xDoc = new XmlDocument();
xDoc.AppendChild( xDoc.CreateElement("root"));
string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie" };
foreach (string node in NodeArray)
{
XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element, node.Split('|')[0], null);
//xmlNode.Value = node.Split('|')[0];
xmlNode.InnerText = node.Split('|')[1];
xDoc.DocumentElement.AppendChild(xmlNode);
}
It is not possible to have that XML structure as XML MUST have a single root element. You may want to try:
<?xml version="1.0" encoding="ISO-8859-1"?>
<items>
<Fruits>Fruit</Fruits>
<Vegetables>Veggie</Vegetables>
</items>

How to read single node value from xml file

Hi i am trying to get value from xml but it shows node null.
Here is my xml file.
<?xml version="1.0" encoding="utf-8"?>
<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.cfhdocmail.com/TestAPI2/Result.xsd https://www.cfhdocmail.com/TestAPI2/Result.xsd" xmlns="https://www.cfhdocmail.com/TestAPI2/Result.xsd">
<data>
<key>MailingGUID</key>
<value>0aa2b2e3-7afa-4002-ab2f-9eb4cbe33ae7</value>
</data>
<data>
<key>OrderRef</key>
<value>52186</value>
</data>
</result>
I want to get "MailingGUID" value.
Here is the code that i have tried:
private void readXML()
{
XmlDocument xml = new XmlDocument();
// You'll need to put the correct path to your xml file here
xml.Load(Server.MapPath("~/XmlFile11.xml"));
// Select a specific node
XmlNode node = xml.SelectSingleNode("result/data/value");
// Get its value
string name = node.InnerText;
}
Please tell me how i can get MailingGUID value.
Thanks
UPDATE:
I think there might be something wrong with your schemas, I removed references to them and your code worked fine. I tried this:
const string str = "<?xml version=\"1.0\" encoding=\"utf-8\"?><result><data><key>MailingGUID</key><value>0aa2b2e3-7afa-4002-ab2f-9eb4cbe33ae7</value></data><data><key>OrderRef</key><value>52186</value></data></result>";
var xml = new XmlDocument();
xml.LoadXml(str);
xml.DocumentElement.SelectSingleNode("/result/data/value").InnerText
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Parsing of xml is done here
Document doc = builder.parse(new File("C:\\Users\\User_Name\\Documents\\My Received Files\\PDSL_ABM.xml"));
//Here we get the root element of XML and print out
doc.getDocumentElement().normalize();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
NodeList list = doc.getElementsByTagName("MailingGUID");
int totalMailingGUID =list.getLength();
System.out.println("Total no of MailingGUID : " + totalSupplierPartID);
//Traversing all the elements from the list and printing out its data
for (int i = 0; i < list.getLength(); i++) {
//Getting one node from the list.
Node childNode = list.item(i);
System.out.println("MailingGUID : " + childNode.getTextContent());
}

removing namespace from xml

I have an xml as shown:
<?xml version="1.0" encoding="utf-8"?>
<Query_advanced>
<Query>hy</Query>
<Attribute Name1="Patient's Age" Value1="23" xmlns="xyz"/>
<Attribute Name1="Patient's Birth Date" Value1="24/12/1988" xmlns="xyz"/>
<Attribute Name1="Patient's Name" Value1="xyz" xmlns="xyz" />
</Query_advanced>
I need to read through the xml to get the values of Name1 and of Value1, but im unable to do so with the xmlns there. Is there any way i could do so? Ive tried using:
XmlNamespaceManager xnm = new XmlNamespaceManager(xdoc.NameTable);
xnm.RemoveNamespace("Attribute", "xyz");
I think you've not to remove the namespace, but you've to add it to the XmlNameSpaceManager, in order to use a prefix (as #John Saunders comments), for example, in a XPath expression.
Try this:
XmlNamespaceManager xnm = new XmlNamespaceManager(xdoc.NameTable);
xnm.AddNamespace("a", "xyz");
// Cycle through the Attribute nodes
foreach (XmlNode node in xdoc.SelectNodes("//Query_advanced/a:Attribute", xnm))
{
// And read the attributes of the node
string NameAttribute = node.Attributes["Name1"].Value;
string ValueAttribute = node.Attributes["Value1"].Value;
}
Use XmlReader or XmlTextReader if you have a file.
Here an example:
http://msdn.microsoft.com/en-us/library/cc189056(v=vs.95).aspx
In your example Attribute is a xml tag, not a namespace. Name1 and Value1 are xml attributes of the tag Attribute.
So you need to read the attributes of the tag Attribute.
Let xmlString is the xml you want to parse:
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
while(reader.ReadToFollowing("Attribute")){ //loop read Attribute tag
reader.MoveToFirstAttribute();
string Name1 = reader.Value; //do something with Name1
reader.MoveToNextAttribute();
string Value1 = reader.Value; //do something with Value1
}
}
THanks for all your suggestions! I managed to do it this way:
private void QueryXML()
{
XmlDocument query_xml = new XmlDocument();
query_xml.Load("Query_1.xml");
XmlNodeList elements = query_xml.GetElementsByTagName("Attribute");
string[] s = new string[elements.Count];
for (int i = 0; i < elements.Count; i++)
{
string attrVal = elements[i].Attributes["Value1"].Value;
Console.Writeline(attrval)
}
Thanks a bunch! :)

XML CDATA Encoding

I am trying to build an XML document in C# with CDATA to hold the text inside an element. For example..
<email>
<![CDATA[test#test.com]]>
</email>
However, when I get the InnerXml property of the document, the CDATA has been reformatted so the InnerXml string looks like the below which fails.
<email>
<![CDATA[test#test.com]]>
</email>
How can I keep the original format when accessing the string of the XML?
Cheers
Don't use InnerText: use XmlDocument.CreateCDataSection:
using System;
using System.Xml;
public class Test
{
static void Main()
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
XmlElement email = doc.CreateElement("email");
XmlNode cdata = doc.CreateCDataSection("test#test.com");
doc.AppendChild(root);
root.AppendChild(email);
email.AppendChild(cdata);
Console.WriteLine(doc.InnerXml);
}
}
With XmlDocument:
XmlDocument doc = new XmlDocument();
XmlElement email = (XmlElement)doc.AppendChild(doc.CreateElement("email"));
email.AppendChild(doc.CreateCDataSection("test#test.com"));
string xml = doc.OuterXml;
or with XElement:
XElement email = new XElement("email", new XCData("test#test.com"));
string xml = email.ToString();
See XmlDocument::CreateCDataSection Method for information and examples how to create CDATA nodes in an XML Document

Categories