Declaring multiple strings from code - c#

I have something like:
XmlDocument doc = new XmlDocument();
doc.Load(#"D:\filter.xml");
string filter1 = doc.SelectSingleNode("filter/f1").InnerText;
string filter2 = doc.SelectSingleNode("filter/f2").InnerText;
string filter3 = doc.SelectSingleNode("filter/f3").InnerText;
string filter4 = doc.SelectSingleNode("filter/f4").InnerText;
string filter5 = doc.SelectSingleNode("filter/f5").InnerText;
string filter6 = doc.SelectSingleNode("filter/f6").InnerText;
And so on...My question is how could I generate these strings in a loop?something like.
XmlDocument doc = new XmlDocument();
doc.Load(#"D:\filter.xml");
for (int i = 0; i < 7; i++)
{
string filter + i = doc.SelectSingleNode("filter/f" + i).InnerText;;
}

Fill a List<string>:
List<string> filterList = new List<string>();
for (int i = 0; i < 7; i++)
{
filterList.Add(doc.SelectSingleNode("filter/f" + i).InnerText);
}
Now you can access them via index, f.e. filter 5:
string filter5 = filterList[4]; // zero based

You want to use a collection, like List<string>:
XmlDocument doc = new XmlDocument();
doc.Load(#"D:\filter.xml");
var myList = new List<strinig>;
for (int i = 0; i < 7; i++)
{
myList.Add(doc.SelectSingleNode("filter/f" + i).InnerText);
}
Then you can use the list by referencing a string's index:
myValue = myList[3];

Use Collection to store String and this is how you can add string to collection from the XML.
doc.Load(#"D:\filter.xml");
List<string> filter = new List<string>();
foreach (XmlNode item in doc.SelectSingleNode("filter").ChildNodes)
{
filter.Add(item.InnerText.ToString());
}
Hope this helps.

Related

How to read data from any file and insert to class object using c#

I am reading a data from CSV file and trying to add to object. but when i add new record by looping through records the data in object is getting overridden.
public static void Process()
{
var path= #"ABC.csv";
var header = false;
var lines = System.IO.File.ReadAllLines(filePath);
var element = new List<Content>();
var mapTo = new Content();
for (var i = 0; i < lines.Length; i++)
{
var t = lines[i];
if (!header)
{
header = true;
}
else
{
var data = t.Split(',');
mapTo.Key= data[0];
mapTo.Name= data[1];
mapTo.Number= data[2];
mapTo.Date= data[3];
element.Add(mapTo);
}
}
var result = element;
}
so here when i try to add mapTo to element all the content in element variable is getting overridden.Can anybody suggest what's wrong i am doing here.
Move var mapTo = new Content(); into the for loop. Otherwise you have the same instance of Content for each loop iteration which gets overriden by the assigenments in the for loop.
public static void Process()
{
var path= #"ABC.csv";
var header = false;
var lines = System.IO.File.ReadAllLines(filePath);
var element = new List<Content>();
for (var i = 0; i < lines.Length; i++)
{
var mapTo = new Content(); //here
var t = lines[i];
if (!header)
{
header = true;
}
else
{
var data = t.Split(',');
mapTo.Key= data[0];
mapTo.Name= data[1];
mapTo.Number= data[2];
mapTo.Date= data[3];
element.Add(mapTo);
}
}
var result = element;
}

How to make 2 columns in dropdownlist while parsing XML?

remcl3.Wcl3Client client = new remcl3.Wcl3Client();
string rrs = client.getsql("sabatini", "ZXCqwe1920",112, w);
string xml = #rrs;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList elemList = doc.GetElementsByTagName("AC_NO");
XmlNodeList elem = doc.GetElementsByTagName("AC_NAME");
for (int i = 0; i < elemList.Count; i++)
{
rem_no.DataTextField = doc.GetElementsByTagName("AC_NO").ToString();
rem_no.Items.Add(elemList[i].InnerXml);
rem_no.DataValueField = doc.GetElementsByTagName("AC_NAME").ToString();
rem_no.Items.Add(elem[i].InnerXml);
}
I'm trying to parse XML with two fields ac_no, ac_name using C# ASP.NET and put the data value, data text for the dropdownlist and bind the data value.
I have tried the following code but with no luck:
I want to bind the ac_no and show the ac_name; any help?
You can use a DataTable:
C# Code:
remcl3.Wcl3Client client = new remcl3.Wcl3Client();
string rrs = client.getsql("sabatini", "ZXCqwe1920",112, w);
string xml = #rrs;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList elemList = doc.GetElementsByTagName("AC_NO");
XmlNodeList elem = doc.GetElementsByTagName("AC_NAME");
DataTable table = new DataTable();
table.Columns.Add("AC_NO");
table.Columns.Add("AC_NAME");
for (int i = 0; i < elemList.Count; i++)
{
DataRow row = table.NewRow();
var value = elemList[i].InnerXml;
var text = elem[i].InnerXml;
row["AC_NO"] = value;
row["AC_NAME"] = text;
table.Rows.Add(row);
}
// Configure your Dropdownlist
rem_no.DataSource = table;
rem_no.ValueMember = "AC_NO";
rem_no.DisplayMember = "AC_NAME";
rem_no.SelectedIndex = -1;
Or use a ListItem:
C# Code:
remcl3.Wcl3Client client = new remcl3.Wcl3Client();
string rrs = client.getsql("sabatini", "ZXCqwe1920",112, w);
string xml = #rrs;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList elemList = doc.GetElementsByTagName("AC_NO");
XmlNodeList elem = doc.GetElementsByTagName("AC_NAME");
for (int i = 0; i < elemList.Count; i++)
{
var value = elemList[i].InnerXml;
var text = elem[i].InnerXml;
rem_no.Items.Add(new ListItem(text, value));
}

Add multiple elements to XML document

Im trying to create a XML file with the next structure
<tdes1></tdes1>
<tdes2></tdes2>
<tdes3></tdes3>
but i am getting error when trying to append the elemnt
This is what i was trying to do
var xmlLlavesTDES = new XmlDocument();
xmlLlavesTDES.AppendChild(xmlLlavesTDES.CreateXmlDeclaration("1.0", "UTF-8", null));
// XElement test = new XElement("test");
for (var i = 0; i < this.llavesTDESArray.Length; i++)
{
var llavesTDESEncriptadas = encriptador.Encriptar(this.llavesTDESArray[i], this.llavePublicaEsclavo);
var llaveNum = i + 1;
XmlElement nodo= xmlLlavesTDES.CreateElement("tdes" + llaveNum);
nodo.InnerText = llavesTDESEncriptadas;
xmlLlavesTDES.AppendChild(nodo);
}
The error I get is This document already has a 'DocumentElement' node
i recommend an aproach similar to this using Linq instead of your approach:
//using System.Xml.Linq;
var xmlLlavesTDES = new XDocument();
XElement rootElement = new XElement("AllMyValues");
for (var i = 0; i < this.llavesTDESArray.Length; i++)
{
var llavesTDESEncriptadas = encriptador.Encriptar(this.llavesTDESArray[i], this.llavePublicaEsclavo);
var llaveNum = i + 1;
XElement nodo = new XElement("tdes" + llaveNum);
nodo.Value = llavesTDESEncriptadas;
rootElement.Add(nodo);
}
xmlLlavesTDES.Add(rootElement);

How to return variable which in declared with in loop c#

private XElement AuthorSeparate(List<string> authorName)
{
string surName = string.Empty;
string initalName = string.Empty;
string givenName = string.Empty;
int j = 1;
for (int i = 0; i < authorName.Count; i++)
{
XElement Author = new XElement("author");
Author.Add(new XAttribute("Seq", j));
else
{
char[] initalArray = splitedName[0].ToCharArray();
initalName = initalArray[0] + '.'.ToString();
surName = splitedName.LastOrDefault();
splitedName = splitedName.Reverse().Skip(1).Reverse().ToArray();
givenName = string.Join(" ", splitedName);
}
if (!string.IsNullOrEmpty(initalName))
{
XElement InitalElement = new XElement("initials", initalName);
Author.Add(InitalElement);
}
if (!string.IsNullOrEmpty(surName))
{
XElement SurnameElement = new XElement("surname", surName);
Author.Add(SurnameElement);
}
if (!string.IsNullOrEmpty(givenName))
{
XElement GivenNameElement = new XElement("given-name", givenName);
Author.Add(GivenNameElement);
}
}
return Author;
}
This is my method.. Form this method i need to return xelement. in this method i declared xelement in for loop. after for loop completed i need to return that xelement named as author. how to return that xelement?
If you declare the variable in the loop, you can use it only inside the loop. So in your case, you should declare it outside of the loop because you can't put the return statement inside for loop.
Edit:
private ArrayList AuthorSeparate(List<string> authorName)
{
string surName = string.Empty;
string initalName = string.Empty;
string givenName = string.Empty;
int j = 1;
ArrayList authors = new ArrayList();
for (int i = 0; i < authorName.Count; i++)
{
XElement Author = new XElement("author");
Author.Add(new XAttribute("Seq", j));
else
{
char[] initalArray = splitedName[0].ToCharArray();
initalName = initalArray[0] + '.'.ToString();
surName = splitedName.LastOrDefault();
splitedName = splitedName.Reverse().Skip(1).Reverse().ToArray();
givenName = string.Join(" ", splitedName);
}
if (!string.IsNullOrEmpty(initalName))
{
XElement InitalElement = new XElement("initials", initalName);
Author.Add(InitalElement);
}
if (!string.IsNullOrEmpty(surName))
{
XElement SurnameElement = new XElement("surname", surName);
Author.Add(SurnameElement);
}
if (!string.IsNullOrEmpty(givenName))
{
XElement GivenNameElement = new XElement("given-name", givenName);
Author.Add(GivenNameElement);
}
authors.Add(Author)
}
return authors;
}
If you want to create an XElement in each round, you can put them all in an ArrayList then return it.
I believe instead of returning XElement from function you should return List of XElement.
So you can write something like this:
private List<XElement> AuthorSeparate(List<string> authorName)
{
string surName = string.Empty;
string initalName = string.Empty;
string givenName = string.Empty;
int j = 1;
var AuthorList = new List<XElement>();
for (int i = 0; i < authorName.Count; i++)
{
XElement Author = new XElement("author");
Author.Add(new XAttribute("Seq", j));
else
{
char[] initalArray = splitedName[0].ToCharArray();
initalName = initalArray[0] + '.'.ToString();
surName = splitedName.LastOrDefault();
splitedName = splitedName.Reverse().Skip(1).Reverse().ToArray();
givenName = string.Join(" ", splitedName);
}
if (!string.IsNullOrEmpty(initalName))
{
XElement InitalElement = new XElement("initials", initalName);
Author.Add(InitalElement);
}
if (!string.IsNullOrEmpty(surName))
{
XElement SurnameElement = new XElement("surname", surName);
Author.Add(SurnameElement);
}
if (!string.IsNullOrEmpty(givenName))
{
XElement GivenNameElement = new XElement("given-name", givenName);
Author.Add(GivenNameElement);
}
AuthorList.Add(Author);
}
return AuthorList;
}
It will be better to return the list in the way above because here you will get a new XElement for every iteration of the loop.

To return the multiple values from for loop

I have parsed the xml document and used a for loop to loop for getting different values in string, but when I try to return the value I get only the last value obtained, I want to return all the individual values so that I can store that values in any file format,
Below is my code,
XmlDocument xmlDOC = new XmlDocument();
xmlDOC.LoadXml(periodID_Value_Before_OffSet); // string storing my XML
var value = xmlDOC.GetElementsByTagName("value");
var xmlActions = new string[value.Count];
string values = "";
string Period1 = "";
string periodlevel_period1 = "";
var listOfStrings = new List<string>();
string modified_listofstrings = listOfStrings.ToString();
string arrayOfStrings = "";
for (int i = 0; i < value.Count; i++)
{
var xmlAttributeCollection = value[i].Attributes;
if (xmlAttributeCollection != null)
{
var action = xmlAttributeCollection["periodid"];
xmlActions[i] = action.Value;
values += action.Value + ",";
string vals = values.Split(',')[1];
string counts = values;
string[] periods = counts.Split(',');
Period1 = periods[i];
// periodlevel_period1 = Client.GetAttributeAsString(sessionId, Period1, "name", "");
modified_listofstrings = Client.GetAttributeAsString(sessionId, Period1, "name", "");
modified_listofstrings.ToArray().ToString();
//listOfStrings = periodlevel_period1;
}
}
return modified_listofstrings;
This modified_listofstrings string only return last on value, I want to return the array of the values all obtained while looping.
----------Updated question----------
below is my Sample XMl
<string xmlns="http://tempuri.org/">
<ResultSetHierarchy totalResultsReturned="1" totalResults="1" firstIndex="0" maxCount="-1">
<object id="SC.1938773693.238">
<measure.values>
<series id="SC.1938773693.108280985">
<value periodid="SC.1938773693.394400760" value="17" />
<value periodid="SC.1938773693.1282504058" value="15" />
<value periodid="SC.1938773693.1631528570" value="13" />
</series>
</object>
</ResultSetHierarchy>
</string>
I want output as "SC.1938773693.394400760":"17" and so on for all periodid
Based on the provided information I have updated the answer.
List<string> items = new List<string>();
XmlDocument xmlDOC = new XmlDocument();
xmlDOC.Load(#"E:\Delete Me\ConsoleApplication1\ConsoleApplication1\bin\Debug\List.xml");
var elements = xmlDOC.GetElementsByTagName("value");
foreach (var item in elements)
{
XmlElement value = (XmlElement)item;
items.Add(string.Format("{0}:{1}", value.GetAttribute("periodid"), value.GetAttribute("value")));
}
It looks like you're trying to:
Load an XmlDocument
Get a list of all the attributes of name 'periodid'
Look each periodid up using a webservice call
Return a list of the lookup results
If that is correct, the following method should do what you need:
public List<string> GetListOfData()
{
XmlDocument xmlDOC = new XmlDocument();
xmlDOC.LoadXml("<Html><value periodid='Yabba'>YabbaValue</value><value periodid='Dabba'>DabbaValue</value><value periodid='Doo'>DooValue</value></Html>"); // string storing my XML
var value = xmlDOC.GetElementsByTagName("value");
var listOfStrings = new List<string>();
for (int i = 0; i < value.Count; i++)
{
var xmlAttributeCollection = value[i].Attributes;
if (xmlAttributeCollection != null)
{
var action = xmlAttributeCollection["periodid"];
string Period1 = action.Value;
listOfStrings.Add(QPR_webService_Client.GetAttributeAsString(sessionId, Period1, "name", "") + ":" + value[i].InnerText);
}
}
return listOfStrings;
}

Categories

Resources