<root>
<row>
<linksclicked>http://www.examiner.com/</linksclicked>
<clickedcount>34</clickedcount>
</row>
<row>
<linksclicked>http://www.sample123.com</linksclicked>
<clickedcount>16</clickedcount>
</row>
<row>
<linksclicked>http://www.testing123.com</linksclicked>
<clickedcount>14</clickedcount>
</row>
</root>
I have xml like above in a string and i have class like below
public class Row
{
public string linksclicked { get; set; }
public int clickedcount { get; set; }
}
How can i convert the xml string to a list of Row Object
You can use LINQ to XML:
var doc = XDocument.Parse(xmlString);
var items = (from r in doc.Root.Elements("row")
select new Row()
{
linksclicked = (string) r.Element("linksclicked"),
clickedcount = (int) r.Element("clickedcount")
}).ToList();
This approach can be a safer one to avoid exceptions in case if xml result becomes empty from the server call.
string xmlString = "<School><Student><Id>2</Id><Name>dummy</Name><Section>12</Section></Student><Student><Id>3</Id><Name>dummy</Name><Section>11</Section></Student></School>";
XDocument doc = new XDocument();
//Check for empty string.
if (!string.IsNullOrEmpty(xmlString))
{
doc = XDocument.Parse(xmlString);
}
List<Student> students = new List<Student>();
//Check if xml has any elements
if(!string.IsNullOrEmpty(xmlString) && doc.Root.Elements().Any())
{
students = doc.Descendants("Student").Select(d =>
new Student
{
id=d.Element("Id").Value,
name=d.Element("Name").Value,
section=d.Element("Section").Value
}).ToList();
}
public class Student{public string id; public string name; public string section;}
Check the demo fiddle Demo
You can use an XMLSerializer to deserialize the a property of type List and assign the tag name to the property as root.
However, you'll need the XML tag at the starting of the file.
U can write your own XML parser using XElement.
You can the list of row nodes, parse each of them n load them in a list.
XElement rootNode = XElement.Load(filepath);
List<XElement> nodes = rootNode.Descendants().Where(t=> t.Name.ToString().Equals("row"));
for each tag you can create an object Row and fill its properties based on child tags.
Hope it helps
You can try this piece of code
string xml = "<Ids><id>1</id><id>2</id></Ids>";
ArrayList list = new ArrayList();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList idNodes = doc.SelectNodes("Ids/id");
foreach (XmlNode node in idNodes)
list.Add(node.InnerText);
Try this one:
var xml = #"
<root>
<row>
<linksclicked>http://www.examiner.com/</linksclicked>
<clickedcount>34</clickedcount>
</row>
<row>
<linksclicked>http://www.sample123.com</linksclicked>
<clickedcount>16</clickedcount>
</row>
<row>
<linksclicked>http://www.testing123.com</linksclicked>
<clickedcount>14</clickedcount>
</row>
</root>";
var xElems = XDocument.Parse(xmlString);
var xRow = doc.Root.Elements("row");
List<Row> rowList = (from rowTags in xRow
let clickCount = 0
let isClickCountOk = Int32.TryParse((rowTags.Element("clickedcount").Value, clickCount);
where !string.IsNullOrEmpty(rowTags.Element("linksclicked").Value) &&
!string.IsNullOrEmpty(rowTags.Element("clickedcount").Value)
select new Row()
{
linksclicked = rowTags.Element("linksclicked").Value,
clickedcount = clickCount
}).ToList();
Related
I have a XML file that looks like this:
<Info>
<ID>1</ID>
<Result>
<ID>2</ID>
</Result>
</Info>
I want to count how many Info/Result/ID I have in this file.
I am doing this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("myFile.xml");
xmlNodeList MyList = xmlDoc.GetElementsByTagName("Info/Result/ID");
int totalCount = MyList.Count;
// other logic...
The method GetElementsByTagName does not find any "ID"-field.
I want to get the "ID = 2".
How do I do that?
To count all the nodes in "Info/Result/ID" path use this..
var count = xmlDoc.SelectNodes("Info/Result/ID")?.Count ?? 0;
To process these nodes
var nodes = xmlDoc.SelectNodes("Info/Result/ID");
foreach (XmlNode node in nodes) {
var idValue = node.InnerText
// do something
}
Got it working, hereĀ“s how:
public static void MyCountExample(string myXml, out int myID)
{
var stream = new MemoryStream(Encoding.UTF8.GetBytes(myXml ?? ""));
var reader = XmlReader.Create(stream);
myID= 0;
reader.IsStartElement("Info");
while (!reader.EOF)
{
if (reader.ReadToFollowing("Result"))
{
if (reader.ReadToDescendant("ID"))
{
myID++;
else
{
return somethingElse();
}
......
I need to parse xml but my code just parses one title not all.
How can I parse part ?
This is my code:
CustomResponse itemCustom = new CustomResponse ();
XDocument response = XDocument.Parse(responseXml);
XElement rootElement = response.Root;
foreach (XElement sellResponse in rootElement.Elements())
{
itemCustom .ErrorCode = sellResponse.Element("ErrorCode").Value;
itemCustom .ErrorMessage = sellResponse.Element("ErrorMessage").Value;
itemCustom .CustomerID= sellResponse.Element("CustomerID").Value;
itemCustom .CustomerType= sellResponse.Element("CustomerType").Value;
}
This is my xml:
<?xml version="1.0" encoding="utf-8"?>
<TINS_XML_DATA>
<Header>
<ErrorCode>WAATS</ErrorCode>
<ErrorMessage>UTL</ErrorMessage>
</Header>
<Customer>
<CustomerID>UTL11111111111111111111</CustomerID>
<CustomerType>NSell</CustomerType>
</Customer>
</TINS_XML_DATA>
Try something like this:
foreach (XElement sellResponse in rootElement.Elements())
{
if (sellResponse.Name == "Header")
{
itemCustom.ErrorCode = sellResponse.Element("ErrorCode").Value;
itemCustom.ErrorMessage = sellResponse.Element("ErrorMessage").Value;
}
else if (sellResponse.Name == "Customer")
{
itemCustom.CustomerID = sellResponse.Element("CustomerID").Value;
itemCustom.CustomerType = sellResponse.Element("CustomerType").Value;
}
}
Update: You could also use XPath to find required elements as like below:
var xDoc = new XmlDocument();
xDoc.LoadXml(xml);
var errorMessage = xDoc.SelectNodes("//ErrorMessage")[0].InnerText;
This is my solved:
var xDoc = new XmlDocument();
xDoc.LoadXml(responseXml);
itemSell.ErrorCode = xDoc.SelectNodes("//ErrorCode")[0].InnerText;
itemSell.ErrorMessage = xDoc.SelectNodes("//ErrorMessage")[0].InnerText;
itemSell.CustomerID= xDoc.SelectNodes("//CustomerID")[0].InnerText;
I want to iterate the data from XMLElement. In List i have 10 row of records . each row contains again list of values. In row, each values need to store into somString type.
Below is the XMLElement getting from List
<ROW id="1">
<D n="6721">10128</D>
<D n="6724">CL</D>
<D n="6771">*</D>
<D n="6773">ACT</D>
<D n="6774">PHON</D>
<D n="6775">04-MAR-2018 21:54</D>
<D n="6779">MEP-IU</D>
<D n="6780">MEP-IU-010</D>
<D n="6782">CWP2B19-113</D>
<D n="6792">11410</D>
<D n="6809"/>
<D n="6880"/>
<D n="11651">Tap is not working in the Back of the Apt
Name: Alex
Contact : 971-566826978</D>
<D n="100410">40977</D>
<D n="101312">AHMED.ALI#MERAAS.AE</D>
<D n="101313">HANDOVER</D>
</ROW>
I tried this code for i tried to iterating data, but i m getting very 1st element only not remaining elements:
for (int i = 0; i < nodeList.Count; i++)
{
if (nodeList[i].InnerText.Length > 0)
{
string name =(string) i.FirstChild.Value;
MessageBox.Show(nodeList[i].InnerText);
}
}
But i m getting filed column value only .. how to get remaining data from XMLElement.
In List i have 10 row of records . each row contains again list of values. In row, each values need to store into somString type.
I want to extract list of all records from response. I m not sure how to go about writing a code for to filter the data.
Kindly refer some sample for this one.
Here is a quick and dirty way to get at the values, this can be improved by removing the hard-coded values and checking for objects prior to accessing them.
EDIT: XML structure is from here.
using (var stream = new StreamReader("Response.xml"))
{
XDocument doc = XDocument.Load(stream);
var nodes = doc.Elements().Descendants()
.Where(x => x.Name == XName.Get("ROW", "http://schemas.datastream.net/MP_functions/MP0118_GetGridHeaderData_001_Result"));
foreach (var node in nodes)
{
if (node.FirstAttribute != null)
{
var firstAttribute = node.FirstAttribute;
Console.WriteLine($"{firstAttribute.Name.LocalName} - {firstAttribute.Value}");
var children = node.Descendants();
if (children.Count() > 0)
{
foreach (var child in children)
{
Console.WriteLine($"{child.FirstAttribute.Value}:{child.Value}");
}
}
Console.WriteLine("----------------------------------");
}
}
}
using (WebResponse response = httpWebRequest.GetResponse())
{
using (StreamReader streamreader = new StreamReader(response.GetResponseStream()))
{
string result1 = streamreader.ReadToEnd();
MessageBox.Show(result1);
xmlDocument = new XmlDocument();
xmlDocument.LoadXml(result1);
XmlNodeList nodeList;
if (xmlDocument.DocumentElement.Attributes["xmlns:soapenv"] != null)
{
string xmlns = xmlDocument.DocumentElement.Attributes["xmlns:soapenv"].Value;
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
nsmgr.AddNamespace("df", "http://schemas.datastream.net/MP_functions/MP0118_GetGridHeaderData_001_Result");
nodeList = xmlDocument.SelectNodes("/soapenv:Envelope/soapenv:Body/df:MP0118_GetGridHeaderData_001_Result/df:GRIDRESULT/df:GRID/df:DATA/df:ROW[*]", nsmgr);
}
else
{
nodeList = xmlDocument.SelectNodes("/soapenv:Envelope/soapenv:Body/df:MP0118_GetGridHeaderData_001_Result/df:GRIDRESULT/df:GRID/df:DATA/df:ROW[*]");
}
for (int i = 0; i < nodeList.Count; i++)
{
if (nodeList[i].InnerText.Length > 0)
{
String ctr_code = nodeList[i].ChildNodes[0].InnerText;
String ctr_status = nodeList[i].ChildNodes[1].InnerText;
String ctr_org = nodeList[i].ChildNodes[2].InnerText;
String ctr_type = nodeList[i].ChildNodes[3].InnerText;
String ctr_contactsource = nodeList[i].ChildNodes[4].InnerText;
String ctr_created = nodeList[i].ChildNodes[5].InnerText;
String ctr_servicecategory = nodeList[i].ChildNodes[6].InnerText;
String ctr_serviceproblem = nodeList[i].ChildNodes[7].InnerText;
String ctr_object = nodeList[i].ChildNodes[8].InnerText;
String ctr_contactinfoid = nodeList[i].ChildNodes[9].InnerText;
String ctr_contactnote = nodeList[i].ChildNodes[10].InnerText;
String ctr_desc = nodeList[i].ChildNodes[11].InnerText;
String ctr_note = nodeList[i].ChildNodes[12].InnerText;
String ctr_event = nodeList[i].ChildNodes[13].InnerText;
String ctr_createdby = nodeList[i].ChildNodes[14].InnerText;
String ctr_mrc = nodeList[i].ChildNodes[15].InnerText;
}
}
}
}
}
I have a root XML which is like this:
<Root xmlns="http://schemas.datacontract.org/2004/07/" xmlns:t="http://www.w3.org/2001/XMLSchema-instance">
<Element1>somevalue</Element1>
<Data/>
<Root>
I need to add few customer related informaiton like (Name, Age etc) under Data Element Node. So, the result I expect is follows:
<Root xmlns="http://schemas.datacontract.org/2004/07/" xmlns:t="http://www.w3.org/2001/XMLSchema-instance">
<Element1>somevalue</Element1>
<Data>
<Name t:type="xs:string" xmlns="" xmlns:s="http://www.w3.org/2001/XMLSchema">Elvis</Name>
<Address t:type="xs:string" xmlns="" xmlns:s="http://www.w3.org/2001/XMLSchema">Some address</Address>
</Data>
<Root>
How can I achieve this? I am using C#, .net 4.0.
I was trying out the below code, but didn't get the result I was expecting:
string strTemplate = "<Root xmlns='http://schemas.datacontract.org/2004/07/' xmlns:t='http://www.w3.org/2001/XMLSchema-instance'><Element1>somevalue</Element1><Data/></Root>";
XDocument doc = XDocument.Parse(strTemplate);
XElement rootElement = doc.Root;
XElement dataElement = null;
foreach (XElement descendant in rootElement.Descendants())
{
if (descendant.Name.LocalName == "Data")
{
dataElement = descendant;
break;
}
}
string cusData = "<CustData><Name>Elvis</Name><Address>XYZ</Address></CustData>";
XElement customerElements = XElement.Parse(cusData);
if (dataElement != null)
{
foreach (XElement custAttributes in customerElements.Descendants())
{
XNamespace t = "http://www.w3.org/2001/XMLSchema-instance";
var attribute = new XAttribute(t + "type", "xs:string");
var attribute1 = new XAttribute(XNamespace.Xmlns + "s", "http://www.w3.org/2001/XMLSchema");
XElement element = new XElement(custAttributes.Name, attribute, attribute1);
element.Value = custAttributes.Value;
dataElement.Add(element);
}
}
string strPayload = doc.ToString();
When I execute the code I get the following:
<Data xmlns="http://schemas.datacontract.org/2004/07/">
<Name t:type="xs:string" xmlns:t="http://www.w3.org/2001/XMLSchema-instance" xmlns="">Elvis</Name>
<Address t:type="xs:string" xmlns:t="http://www.w3.org/2001/XMLSchema-instance" xmlns="">XYZ</Address>
</Data>
Any help appreciated!
Thanks,
M
Iv got two DB tables. One containing types(Id, Name) and the other holds datapoints (RefId, Date, Value) that are referenced by the types. I need to create a XML file with the following strukture:
<?xml version='1.0' encoding='utf-8' ?>
<root>
<type>
<name></name>
<data>
<date></date>
<temp></temp>
</data>
<data>
<date></date>
<temp></temp>
</data>
<data>
<date></date>
<temp></temp>
</data>
</type>
</root>
And iv got the following code to do this
public XmlDocument HelloWorld()
{
string tmp = "";
try
{
sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings["NorlanderDBConnection"].ConnectionString;
DataContext db = new DataContext(sqlConn.ConnectionString);
Table<DataType> dataTypes = db.GetTable<DataType>();
Table<DataPoints> dataPoints = db.GetTable<DataPoints>();
var dataT =
from t in dataTypes
select t;
var dataP =
from t in dataTypes
join p in dataPoints on t.Id equals p.RefId
select new
{
Id = t.Id,
Name = t.Name,
Date = p.PointDate,
Value = p.PointValue
};
string xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><root></root>";
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xmlString);
int count = 0;
foreach (var dt in dataT)
{
XmlElement type = xmldoc.CreateElement("type");
XmlElement name = xmldoc.CreateElement("name");
XmlNode nameText = xmldoc.CreateTextNode(dt.Name);
name.AppendChild(nameText);
type.AppendChild(name);
foreach(var dp in dataP.Where(dt.Id = dp.RefId))
{
XmlElement data = xmldoc.CreateElement("data");
XmlElement date = xmldoc.CreateElement("date");
XmlElement temp = xmldoc.CreateElement("temp");
XmlNode dateValue = xmldoc.CreateTextNode(dp.Date.ToString());
date.AppendChild(dateValue);
XmlNode tempValue = xmldoc.CreateTextNode(dp.Value.ToString());
temp.AppendChild(tempValue);
data.AppendChild(date);
data.AppendChild(temp);
type.AppendChild(data);
}
xmldoc.DocumentElement.AppendChild(type);
}
return xmldoc;
}
catch(Exception e)
{
tmp = e.ToString();
}
return null;
}
[Table(Name="DataTypes")]
public class DataType
{
[Column(IsPrimaryKey = true)]
public long Id;
[Column]
public string Name;
}
[Table(Name="DataPoints")]
public class DataPoints
{
[Column]
public long RefId;
[Column]
public DateTime PointDate;
[Column]
public double PointValue;
}
This is not a working code. Im having problems with LINQ and the inner joins. Could someone please help me to get the correct strukture. I hope its kinda clear what im trying to achive.
Best Regards
Marthin
var result =
new XDocument(new XElement("root",
from dt in dataTypes
join dp in dataPoints on dt.Id equals dp.RefId
select new XElement("type",
new XElement("name", dt.Name),
new XElement("data",
new XElement("date", dp.PointDate),
new XElement("temp", dp.PointValue)))));
var result =
new XDocument(new XElement("root",
from dt in dataTypes
select new XElement("type",
new XElement("name", dt.Name),
from dp in dataPoints
where dp.RefId == dt.Id
select new XElement("data",
new XElement("date", dp.PointDate),
new XElement("temp", dp.PointValue)))));