Remove white space from xml node not to attribute value - c#

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);

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;
}

Convert Comma separated string to XML using 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();
}
}

XML Root Element Parsing

I am parsing an xml file using the following which works well but my question is how do I get the value from the tag <themename> because I am using oXmlNodeList for my loop. Just don't want to be writing a separate routine for one tag.
XmlDocument xDoc = new XmlDocument();
List<active_theme> listActiveTheme = new List<active_theme>();
string path = AppDomain.CurrentDomain.BaseDirectory + #"themes\test\configuration.xml";
xDoc.Load(AppDomain.CurrentDomain.BaseDirectory + #"themes\test\configuration.xml");
//select a list of Nodes matching xpath expression
XmlNodeList oXmlNodeList = xDoc.SelectNodes("configuration/masterpages/masterpage");
Guid newGuid = Guid.NewGuid();
foreach (XmlNode x in oXmlNodeList)
{
active_theme activetheme = new active_theme();
string themepage = x.Attributes["page"].Value;
string masterpage = x.Attributes["name"].Value;
activetheme.active_theme_id = newGuid;
activetheme.theme = "Dark";
activetheme.page = themepage;
portalContext.AddToActiveTheme(activetheme);
}
portalContext.SaveChanges();
XML File for theme configuration
<configuration>
<themename>Dark Theme</themename>
<masterpages>
<masterpage page="Contact" name="default.master"></masterpage>
<masterpage page="Default" name="default.master"></masterpage>
<masterpage page="Blue" name="blue.master"></masterpage>
<masterpage page="red" name="red.master"></masterpage>
</masterpages>
</configuration>
I'd use LINQ to XML to start with. Something like this:
var doc = XDocument.Load(...);
var themeName = doc.Root.Element("themename").Value;
Guid themeGuid = Guid.NewGuid();
foreach (var element in doc.Root.Element("masterpages").Elements("masterpage"))
{
ActiveTheme theme = new ActiveTheme
{
ThemeName = themeName,
ActiveThemeId = themeGuid,
Page = element.Attribute("page").Value,
MasterPage = element.Attribute("name").Value
};
portalContent.AddToActiveTheme(theme);
}
portalContext.SaveChanges();

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..

Get element from xml file in c#

I have an xml file which contains an element .
i am storing the content of that xml file as string in csv in one of my projects.i am reading the content of that xml from csv and i want the data of the tag which exists in the content of xml file
I tried like this.
XmlDocument doc = new XmlDocument();
doc.LoadXml(Convert.ToString(dataRow["XML"]));
var temp = doc.GetElementsByTagName("Mail");
but I am not getting the value of Mail into temp.what should i do?
GetElementsByTagName returns XmlNodeList. MSDN Reference
// Display all the book titles.
XmlNodeList elemList = doc.GetElementsByTagName("title");
for (int i=0; i < elemList.Count; i++)
{
Console.WriteLine(elemList[i].InnerXml);
}
Linq solution:
var xDoc = XDocument.Load(dataRow["XML"].ToString());
var mailList = xDoc.Descendants("Mail")
.Select(x => new
{
MailID = x.Element("MailID").Value
})
.ToList();
UPDATE:
XmlDocument doc = new XmlDocument();
doc.LoadXml(Convert.ToString(dataRow["XML"]));
var temp = doc.GetElementsByTagName("Mail");
// loop through all retrieved "Mail" elements
foreach(XmlElement xElem in temp)
{
string sMailText = xElem.InnerText;
}

Categories

Resources