Convert Comma separated string to XML using C# - c#

I want to convert the string to XML.
I have a string like below. It contains the Programming language names.
string lang = "java,php,c#,asp.net,spring,hibernate";
I want to convert this string to XML formal like below:
<Languages>
<lang Name="java"/>
<lang Name="php"/>
<lang Name="c#"/>
<lang Name="asp.net"/>
<lang Name="spring"/>
<lang Name="hibernate"/>
</Languages>
I want to store this XML data in a variable to store later in a database.

It can also be done using Linq-to-XML:
using System.Xml.Linq; // required namespace
XDocument xmlDoc = new XDocument();
XElement xElm = new XElement("Languages",
from l in lang.Split(',')
select new XElement("lang", new XAttribute("Name", l)
)
);
xmlDoc.Add(xElm);

string lang = "java,php,c#,asp.net,spring,hibernate";
string[] langs = lang.Split(',');
XmlDocument document = new XmlDocument();
XmlElement root = document.CreateElement("Languages");
document.AppendChild(root);
for (int i = 0; i < langs.Length; i++)
{
XmlElement langElement = document.CreateElement("lang");
XmlAttribute nameAttr = document.CreateAttribute("Name");
nameAttr.Value = langs[i];
langElement.Attributes.Append(nameAttr);
root.AppendChild(langElement);
}
document.WriteTo(new XmlTextWriter(Console.Out) {
Formatting = Formatting.Indented
});

A short version of what you have done, using Linq and the string manipulation functions
var vales = lang.Split(','); //Splits the CSV
var xmlBody = vales.Select(v => string.Format("<lang Name=\"{0}\"/>",v));
var xml = string.Join(string.Empty, xmlBody); //Potentially add a new line as a seperator
xml = string.Format("<Languages>{0}</Languages>", xml);
The other option is to convert your csv into a model that implements ISerialize and then use the xml serializer. That is more code and not necessarily bad. If you would like to see an example, feel free to ask and I will post an example.

This is working,
class Program
{
static void Main(string[] args)
{
string lang = "java,php,c#,asp.net,spring,hibernate";
StringBuilder sb = new StringBuilder();
sb.AppendFormat("<Languages>");
foreach (string s in lang.Split(','))
{
sb.AppendFormat("<lang Name=\"{0}\"/>", s);
}
sb.AppendFormat("</Languages>");
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
}

Related

getting "null" value for xml

in this xml
<Roots>
<Root Name="cab">element_list</Root>
</Roots>
I want to get the value of attribute Name which is cab and element_list
I have this code
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Root Name=\"cab\">element_list</Root>");
XmlElement root = doc.DocumentElement;
var values = doc.Descendants("Roots").Select(x => new { Name = (string)x.Attribute("Name"), List = (string)x }).ToList();
What I get when I run the debugger is
values> Name = "null", List = "element_list"
I am not understanding why I am getting a null value when I should be getting cab for the attribute Name
XDocument is much easier to work with compared to XmlDocument. Perhaps consider switching to it?
public static void ParseXml()
{
string str = "<Roots><Root Name=\"cab\">element_list</Root></Roots>";
using TextReader textReader = new StringReader(str);
XDocument doc = XDocument.Load(textReader);
var val = doc.Element("Roots").Element("Root").Attribute("Name").Value;
}

Simple C# Linq to Xml

I would like to be able to output the following format using C# Linq to Xml.
<Genres>
<Genre Value="Rock" />
<Genre Value="Metal" />
</Genres>
Consider the following function. I want to evaluate each of the parameters but only add the ones that are not empty strings.
private XmlElement createGenresXml(string str1 = "", string str2 = "Rock", string str3 = "Metal", string str4 = "")
{
'Return XmlElement should look like the Xml above.
}
Thanks! \m/ \m/
public XmlElement CreateGenresXml(string[] args)
{
var el = new XElement("Genres");
el.Add(args.Where(x => !string.IsNullOrWhiteSpace(x)).Select(arg => new XElement("Genre", new XAttribute("Value", arg))));
var doc = new XmlDocument();
using (var reader = el.CreateReader())
{
doc.Load(reader);
}
return doc.DocumentElement;
}
The conversion to XmlElement borrowed from here:

Remove white space from xml node not to attribute value

From below imput xml, i should get output xml as described.
Input Xml
<BPSResponse> <Response> <Code>804</Code> <Text>TagID value is not genuine.</Text> </Response> </BPSResponse>
Output Xml
<BPSResponse><Response><Code>804</Code><Text>TagID value is not genuine.</Text></Response></BPSResponse>
I am creating xml by XElement.
var bpsResponseXml = new XElement("BPSResponse");
for (int i = 0; i < bpsResponseStatusCodes.Count; i++)
{
var bpsResponse = BPSResponseDictionary.GetBPSResponse(bpsResponseStatusCodes[i]);
bpsResponseXml.Add(new XElement("Response",
new XElement("Code", bpsResponse.Code),
new XElement("Text", bpsResponse.Text)));
}
var outPutXml = bpsResponseXml.Value;
I want output xml as formatted above.
var doc = new System.Xml.XmlDocument()
{
PreserveWhitespace = false
};
doc.LoadXml(xmlString);
string flat = doc.OuterXml;
I just have to disable the formatting while converting to string. Below is sample code.
var bpsResponseXml = new XElement("BPSResponse");
bpsResponseXml.Add(new XElement("Response",
new XElement("Code", "804"),
new XElement("Text", "TagID value is not genuine")));
var outPutXml = bpsResponseXml.ToString(System.Xml.Linq.SaveOptions.DisableFormatting);

Read XML file from URL, comes up empty

I am trying to read a XML file from a URL.
The URL and file are fine, they hold currency rates.
When running the code 9 out of 10 times, no content comes back.
Here is the code:
XDocument doc = XDocument.Load("http://www.boi.org.il/currency.xml");
int currID = 0;
Dictionary<int, Currency> curr; // declares the dictionary
curr = new Dictionary<int, Currency>();
var data = from item in doc.Descendants("CURRENCY") // LINQ the informartion from the xml to data variable
select new
{
name = item.Element("NAME").Value,
country = item.Element("COUNTRY").Value,
currencyCode = item.Element("CURRENCYCODE").Value,
rate = Convert.ToDouble(item.Element("RATE").Value),
unit = Convert.ToDouble(item.Element("UNIT").Value),
change = Convert.ToDouble(item.Element("CHANGE").Value),
};
foreach (var xn in data) // run in foreach on the data that we read from the xml and put it in a currency variable into the dictionary
{
Currency currency = new Currency();
currency.Name = xn.name;
currency.Country = xn.country;
currency.CurrencyCode = xn.currencyCode;
currency.Rate = Convert.ToDouble(xn.rate);
currency.Unit = Convert.ToDouble(xn.unit);
currency.Change = Convert.ToDouble(xn.change);
curr.Add(currID, currency);
currID++;
}
foreach (KeyValuePair<int, Currency> entry in curr)
{
Console.WriteLine(entry.Value.CurrencyCode);
}
I have edited the code to see the output, I get nothing.
What am I doing wrong?
Thanks in advance.
#David Faiz It Works!
XmlDocument xDoc = new XmlDocument();
xDoc.Load(#"http://www.boi.org.il//currency.xml");
XmlNodeList xmllist = xDoc.GetElementsByTagName("CURRENCIES");
Console.WriteLine(xmllist.Count);
You have must add // slashes in the URL. That is why u got the 'xmllist.Count' as Zero.
Here's a quick refactor of your code..
XDocument doc = XDocument.Load(#"http://www.boi.org.il/currency.xml");
foreach (XElement elm in doc.Elements)
{
Currency currency = new Currency();
currency.Name = elm.Element("NAME").Value;
currency.Country = elm.Element("COUNTRY").Value;
currency.CurrencyCode = elm.Element("CURRENCYCODE").Value;
currency.Rate = Convert.ToDouble(elm.Element("RATE").Value);
currency.Unit = Convert.ToDouble(elm.Element("UNIT").Value);
currency.Change = Convert.ToDouble(elm.Element("CHANGE").Value);
MessageBox.Show(elm.Element("CURRENCYCODE").Value);
curr.Add(currID, currency);
currID++;
}
However, I'm not sure this addresses the underlying issue you're having..
You could include the System.Net namespace and initialize a XMLHttpRequest object and use the Response stream with the static XDocument.Load() method..

XDocument.ToString() drops XML Encoding Tag

Is there any way to get the xml encoding in the toString() Function?
Example:
xml.Save("myfile.xml");
leads to
<?xml version="1.0" encoding="utf-8"?>
<Cooperations>
<Cooperation>
<CooperationId>xxx</CooperationId>
<CooperationName>Allianz Konzern</CooperationName>
<LogicalCustomers>
But
tb_output.Text = xml.toString();
leads to an output like this
<Cooperations>
<Cooperation>
<CooperationId>xxx</CooperationId>
<CooperationName>Allianz Konzern</CooperationName>
<LogicalCustomers>
...
Either explicitly write out the declaration, or use a StringWriter and call Save():
using System;
using System.IO;
using System.Text;
using System.Xml.Linq;
class Test
{
static void Main()
{
string xml = #"<?xml version='1.0' encoding='utf-8'?>
<Cooperations>
<Cooperation />
</Cooperations>";
XDocument doc = XDocument.Parse(xml);
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
doc.Save(writer);
}
Console.WriteLine(builder);
}
}
You could easily add that as an extension method:
public static string ToStringWithDeclaration(this XDocument doc)
{
if (doc == null)
{
throw new ArgumentNullException("doc");
}
StringBuilder builder = new StringBuilder();
using (TextWriter writer = new StringWriter(builder))
{
doc.Save(writer);
}
return builder.ToString();
}
This has the advantage that it won't go bang if there isn't a declaration :)
Then you can use:
string x = doc.ToStringWithDeclaration();
Note that that will use utf-16 as the encoding, because that's the implicit encoding in StringWriter. You can influence that yourself though by creating a subclass of StringWriter, e.g. to always use UTF-8.
The Declaration property will contain the XML declaration. To get the contents plus declaration, you can do the following:
tb_output.Text = xml.Declaration.ToString() + xml.ToString()
use this:
output.Text = String.Concat(xml.Declaration.ToString() , xml.ToString())
I did like this
string distributorInfo = string.Empty;
XDocument distributors = new XDocument();
//below is important else distributors.Declaration.ToString() throws null exception
distributors.Declaration = new XDeclaration("1.0", "utf-8", "yes");
XElement rootElement = new XElement("Distributors");
XElement distributor = null;
XAttribute id = null;
distributor = new XElement("Distributor");
id = new XAttribute("Id", "12345678");
distributor.Add(id);
rootElement.Add(distributor);
distributor = new XElement("Distributor");
id = new XAttribute("Id", "22222222");
distributor.Add(id);
rootElement.Add(distributor);
distributors.Add(rootElement);
distributorInfo = String.Concat(distributors.Declaration.ToString(), distributors.ToString());
Please see below for what I get in distributorInfo
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Distributors>
<Distributor Id="12345678" />
<Distributor Id="22222222" />
<Distributor Id="11111111" />
</Distributors>
Similar to the other +1 answers, but a bit more detail about the declaration, and a slightly more accurate concatenation.
<xml /> declaration should be on its own line in a formatted XML, so I'm making sure we have the newline added.
NOTE: using Environment.Newline so it will produce the platform specific newline
// Parse xml declaration menthod
XDocument document1 =
XDocument.Parse(#"<?xml version=""1.0"" encoding=""iso-8859-1""?><rss version=""2.0""></rss>");
string result1 =
document1.Declaration.ToString() +
Environment.NewLine +
document1.ToString() ;
// Declare xml declaration method
XDocument document2 =
XDocument.Parse(#"<rss version=""2.0""></rss>");
document2.Declaration =
new XDeclaration("1.0", "iso-8859-1", null);
string result2 =
document2.Declaration.ToString() +
Environment.NewLine +
document2.ToString() ;
Both results produce:
<?xml version="1.0" encoding="iso-8859-1"?>
<rss version="2.0"></rss>
A few of these answers solve the poster's request, but seem overly complicated. Here's a simple extension method that avoids the need for a separate writer, handles a missing declaration and supports the standard ToString SaveOptions parameter.
public static string ToXmlString(this XDocument xdoc, SaveOptions options = SaveOptions.None)
{
var newLine = (options & SaveOptions.DisableFormatting) == SaveOptions.DisableFormatting ? "" : Environment.NewLine;
return xdoc.Declaration == null ? xdoc.ToString(options) : xdoc.Declaration + newLine + xdoc.ToString(options);
}
To use the extension, just replace xml.ToString() with xml.ToXmlString()
You can also use an XmlWriter and call the
Writer.WriteDocType()
method.
string uploadCode = "UploadCode";
string LabName = "LabName";
XElement root = new XElement("TestLabs");
foreach (var item in returnList)
{
root.Add(new XElement("TestLab",
new XElement(uploadCode, item.UploadCode),
new XElement(LabName, item.LabName)
)
);
}
XDocument returnXML = new XDocument(new XDeclaration("1.0", "UTF-8","yes"),
root);
string returnVal;
using (var sw = new MemoryStream())
{
using (var strw = new StreamWriter(sw, System.Text.UTF8Encoding.UTF8))
{
returnXML.Save(strw);
returnVal = System.Text.UTF8Encoding.UTF8.GetString(sw.ToArray());
}
}
// ReturnVal has the string with XML data with XML declaration tag
Extension method to get the Xml Declaration included, using string interpolation here and chose to add a new line after xml declaration as this is the standard I guess.
public static class XDocumentExtensions {
public static string ToStringIncludeXmlDeclaration(this XDocument doc){
return $"({((doc.Declaration != null ? doc.Declaration.ToString() +
Environment.NewLine : string.Empty) + doc.ToString())}";
}
}
}
Usage:
tb_output.Text = xml.ToStringIncludeXmlDeclaration();

Categories

Resources