Convert string to XML using .Net - c#

I store the XML output to String and Again convert this string to XML .I successfully convert XML output to String, but i got problem again converting string to XML.
sample code:
webservice.Service1 objService1 = new webservice.Service1();
String s = objService1.HelloWorld(); //Convert XML output into String
XmlDocument xd = new XmlDocument();
xd.LoadXML(s);
I use LoadXML() method, but i got error
Data at the root level is invalid. Line 1 position 1.
Its grateful, if any body give right code to convert String To XML in c#.
Thank you,

You should use XDocument. XDocument is better than XMLDocument. It is very efficient, simple and easy to use.
Your code :
webservice.Service1 objService1 = new webservice.Service1();
String s = objService1.HelloWorld(); //Convert XML output into String
XmlDocument xd = new XmlDocument();
xd.LoadXml(s);
Solution:
XDocument xd = XDocument.Parse(s);

XmlDocument xd = new XmlDocument();
xd.LoadXml("<root>123</root>");
It works.
You should print the s value and check it is a valid xml string.

Related

How can I preserve entity characters using Xml Document?

My question is simple, but I just can't find why I have this problem and can't resolve it.
I need to read a XML file with values and use them on Unity. For now on, I read my document with its path :
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.DocumentElement;
I have a Namespace Manager already configured.
I read my data like this :
string text = node.SelectSingleNode("x:textRuns/x:DOMTextRun/x:characters", nsmgr).InnerText.Replace("
", Environment.NewLine);
My XML and the data I would like to extract :
<characters>Third occupant
folding seat</characters>
My objective is to replace this entity character : "& #xD;" with an Environment.NewLine.
I tried to :
Formalize the Xml in a file with a replace
Read with an InnerText, and an InnerXml
Make an entity char "detector"
Get the node with all its content (OuterXML)
It looks like this char, however you read it, is exclude and not readable, I just can't have it on my console.
The entity has already been replaced once you extracted InnerText. Problem is, you have a CR (carriage return; 0x0D, \r) instead of a LF (line feed; 0x0A, \n). So replace "\r" by Environment.NewLine:
public static void Main() {
XmlDocument doc = new XmlDocument();
doc.LoadXml("<characters>Third occupant
folding seat</characters>");
string text = doc.SelectSingleNode("/characters").InnerText;
text = text.Replace("\r", Environment.NewLine);
Console.WriteLine(text);
}

String.Split not working to get values

I have an XML which is passes as a string variable to me. I want to get the value of specific tags from that XML. Following is the XML I have and what I'm trying to achieve:
<code>
string xmlData = #"
<HEADER>
<TYPE>AAA</TYPE>
<SUBTYPE>ANNUAL</SUBTYPE>
<TYPEID>12345</TYPEID>
<SUBTYPEID>56789</SUBTYPEID>
<ACTIVITY>C</ACTION>
</HEADER>";
var typeId = data.Split("<TYPEID>")[0]; //Requirement
var activity = data.Split("<ACTIVITY>")[0]; //Requirement
</code>
I know string.Split(); doesn't work here as it requires a single character only. Other alternate is to use regex which seems a bit threatening to me. Although I have tried to work with it but doesn't getting the desired result. Can someone help with the regex code?
You should have used XML Parsing to get the values but since you are trying split to split a string from a string and not char you can choose
string typeId = xmlData.Split(new string[] { "<TYPEID>" }, StringSplitOptions.None)[1];
string typeIdVal = typeId.Split(new string[] { "</TYPEID>" }, StringSplitOptions.None)[0];
and it looks very neat and clean with XML Parsing
XmlDocument xmlDoc= new XmlDocument();
xmlDoc.Load("yourXMLFile.xml");
XmlNodeList XTypeID = xmlDoc.GetElementsByTagName("TYPEID");
string TypeID = XTypeID[0].InnerText;
You can also choose SubString like
string typeidsubstr = xmlData.Substring(xmlData.IndexOf("<TYPEID>") + 8, xmlData.IndexOf("</TYPEID>") - (xmlData.IndexOf("<TYPEID>") + 8));
I used +8 because the length of <TYPEID> is 8 you can also choose it string.length to evaluate the result.
You can use XML Linq objects to parse these.
NB: There is a typo in the ACTIVITY element, the closing tag should be /ACTIVITY, not /ACTION! (I've corrected below)
string xmlData = #"<HEADER>
<TYPE>AAA</TYPE>
<SUBTYPE>ANNUAL</SUBTYPE>
<TYPEID>12345</TYPEID>
<SUBTYPEID>56789</SUBTYPEID>
<ACTIVITY>C</ACTIVITY>
</HEADER>";
var doc = XDocument.Parse(xmlData);
var typeId = doc.Root.Elements("TYPEID").First().Value;
var activity = doc.Root.Elements("ACTIVITY").First().Value;

Extract XML Data from String

I am having a input stream which is generated when I upload a file(XML Type). I need the XML data at code behind. I am having the xml data in string by using
StreamReader stream = new StreamReader(Request.InputStream);
string x = stream.ReadToEnd();
It also contains the following data at the start of the string
------WebKitFormBoundary8na5dBbHc4ydfxVU
Content-Disposition: form-data; name="MyFile"; filename="Test 123.vfc"
Content-Type: application/octet-stream
at the end of the string
------WebKitFormBoundary8na5dBbHc4ydfxVU--
This data is not required for me. Please help me in getting the right XML String.
First you can remove the first three lines and last line from your string.
int n = 3;
string[] lines = str.Split(Environment.NewLine.ToCharArray()).Skip(n).ToArray();
string output = string.Join(Environment.NewLine, lines);
output = output.Remove(str.LastIndexOf(Environment.NewLine));
In your XML string if you don't have a root node then add it like following.
string xmlTxt = "<ROOT>" + xmlString + "</ROOT>";
If you have a root node skip above. For a well format XML string you can just use below code
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.InnerXml = xmlTxt;

convert string to a xml file?

How to save a well formed xml string to a xml file ?
Thanks in advance...
Hi All.... I got the answer
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("WellFormedXMLString");
xmlDoc.Save(#"drive:\name.xml");
What's wrong with simply writing your string to disk?
using (StreamWriter writer = new StreamWriter(#"C:\file.xml"))
{
writer.Write("Xml data");
writer.Flush();
}
or if you want to "test" it:
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(data);
}
catch
{
// Fix it
}
doc.Save(#"C:\file.xml");
You can write any string to disk like so:
File.WriteAllText(#"c:\myfile.xml", yourXmlString);
If you have a string that is not a well-formed xml string and you want to convert that to some other format, you will have to give us some example of what you want to do.
I am no C# programmer, but I guess you need something like this:
xmlwriter tutorial
Save the string straight onto the disk. No need to convert it into XML.
Why do you need xml if it's just a string ? You could save a text file with the variabele name, and the string inside as variable value.
for example
MyTextVar1.txt would contain "MyTestSTring"
then you could get the var by:
var mystring = GetFileAsString( "MyTextVar1.txt" );
The xml document is a text file itself. you only need to change its extension.

Using XDocument to write raw XML

I'm trying to create a spreadsheet in XML Spreadsheet 2003 format (so Excel can read it). I'm writing out the document using the XDocument class, and I need to get a newline in the body of one of the <Cell> tags. Excel, when it reads and writes, requires the files to have the literal string
embedded in the string to correctly show the newline in the spreadsheet. It also writes it out as such.
The problem is that XDocument is writing CR-LF (\r\n) when I have newlines in my data, and it automatically escapes ampersands for me when I try to do a .Replace() on the input string, so I end up with &#10; in my file, which Excel just happily writes out as a string literal.
Is there any way to make XDocument write out the literal
as part of the XML stream? I know I can do it by deriving from XmlTextWriter, or literally just writing out the file with a TextWriter, but I'd prefer not to if possible.
I wonder if it might be better to use XmlWriter directly, and WriteRaw?
A quick check shows that XmlDocument makes a slightly better job of it, but xml and whitespace gets tricky very quickly...
I battled with this problem for a couple of days and finally came up with this solution. I used XMLDocument.Save(Stream) method, then got the formatted XML string from the stream. Then I replaced the &#10; occurrences with
and used the TextWriter to write the string to a file.
string xml = "<?xml version=\"1.0\"?><?mso-application progid='Excel.Sheet'?><Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
xml += "<Styles><Style ss:ID=\"s1\"><Alignment ss:Vertical=\"Center\" ss:WrapText=\"1\"/></Style></Styles>";
xml += "<Worksheet ss:Name=\"Default\"><Table><Column ss:Index=\"1\" ss:AutoFitWidth=\"0\" ss:Width=\"75\" /><Row><Cell ss:StyleID=\"s1\"><Data ss:Type=\"String\">Hello&#10;&#10;World</Data></Cell></Row></Table></Worksheet></Workbook>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xml); //load the xml string
System.IO.MemoryStream stream = new System.IO.MemoryStream();
doc.Save(stream); //save the xml as a formatted string
stream.Position = 0; //reset the stream position since it will be at the end from the Save method
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string formattedXML = reader.ReadToEnd(); //fetch the formatted XML into a string
formattedXML = formattedXML.Replace("&#10;", "
"); //Replace the unhelpful &#10;'s with the wanted endline entity
System.IO.TextWriter writer = new System.IO.StreamWriter("C:\\Temp\test1.xls");
writer.Write(formattedXML); //write the XML to a file
writer.Close();

Categories