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;
}
}
}
}
}
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 have created a XML string and Looping that to get value. But its not entering in foreach loop. But in my other code same loop code is working.
my code is :
XML string:
<SuggestedReadings>
<Suggestion Text="Customer Centricity" Link="http://wdp.wharton.upenn.edu/book/customer-centricity/?utm_source=Coursera&utm_medium=Web&utm_campaign=custcent" SuggBy="Pete Fader�s" />
<Suggestion Text="Global Brand Power" Link="http://wdp.wharton.upenn.edu/books/global-brand-power/?utm_source=Coursera&utm_medium=Web&utm_campaign=glbrpower" SuggBy="Barbara Kahn�s" />
</SuggestedReadings>
Code Is:
string str = CD.SRList.Replace("&", "&");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(str);
XmlNode SuggestionListNode = xmlDoc.SelectSingleNode("/SuggestedReadings/Suggestion");
foreach (XmlNode node in SuggestionListNode)
{
COURSESUGGESTEDREADING CSR = new COURSESUGGESTEDREADING();
var s = db.COURSESUGGESTEDREADINGS.OrderByDescending(o => o.SRID);
CSR.SRID = (s == null ? 0 : s.FirstOrDefault().SRID) + 1;
CSR.COURSEID = LibId;
CSR.TEXT = node.Attributes.GetNamedItem("Text").Value;
CSR.LINK = node.Attributes.GetNamedItem("Link").Value; ;
CSR.SUGBY = node.Attributes.GetNamedItem("SuggBy").Value; ;
CSR.ACTIVEFLAG = "Y";
CSR.CREATEDBY = CD.CreatedBy;
CSR.CREATEDDATE = DateTime.Now;
db.COURSESUGGESTEDREADINGS.Add(CSR);
}
You should use SelectNodes, not SelectSingleNode, since you are trying to get multiple rows out of the XML document.
Use this:
XmlNodeList SuggestionListNode = xmlDoc.SelectNodes("//Suggestion");
foreach (XmlNode node in SuggestionListNode)
{
}
You can try this.
XDocument xdoc = XDocument.Load("data.xml");
var xmlData = from lv1 in xdoc.Descendants("Suggestion")
select new {
Text = lv1.Attribute("Text").Value,
Link = lv1.Attribute("Link").Value,
SuggBy = lv1.Attribute("SuggBy").Value
};
foreach (var item in xmlData){
// your logic here
}
I have an XML file looking like this:
<data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<Alert>warning</Alert>
<Alert2>warning</Alert2>
</row>
</data>
When I use the code below I only get the "Alert"-node. But I wan't "Alert2" as well (and so on...). What am I missing here?
using (XmlReader reader = cmd.ExecuteXmlReader())
{
string xmlFile = "";
while (reader.Read())
{
xmlFile = reader.ReadOuterXml();
}
var doc = new XmlDocument();
doc.LoadXml(xmlFile);
var nodes = doc.SelectNodes("data/row");
if (nodes == null) return columns;
var i = 0;
foreach (XmlNode node in nodes)
{
var column = node.ChildNodes[i].Name;
columns.Add(column);
i++;
}
return columns;
}
Change your loop to the equivalent of:
var doc = new XmlDocument();
doc.LoadXml(xml);
var nodes = doc.SelectNodes("data/row");
int i = 0;
foreach (XmlNode node in nodes)
{
foreach (var child in node.ChildNodes)
{
var element = (XmlElement)child;
string nodeName = element.Name;
string value = element.InnerXml;
i++;
}
}
I need to store the element values which are inside the nodes "member" . I have tried the following code but I can't achieve it. How to get the values. Any help would be appreciated
XML:
<ListInventorySupplyResponse xmlns="http://mws.amazonaws.com/FulfillmentInventory/2010-10-01/">
<ListInventorySupplyResult>
<InventorySupplyList>
<member>
<SellerSKU>043859634910</SellerSKU>
<FNSKU>X000IA4045</FNSKU>
<ASIN>B005YV4DJO</ASIN>
<Condition>NewItem</Condition>
<TotalSupplyQuantity>7</TotalSupplyQuantity>
<InStockSupplyQuantity>7</InStockSupplyQuantity>
<EarliestAvailability>
<TimepointType>Immediately</TimepointType>
</EarliestAvailability>
<SupplyDetail>
</SupplyDetail>
</member>
</InventorySupplyList>
</ListInventorySupplyResult>
<ResponseMetadata>
<RequestId>58c9f4f4-6f60-496a-8d71-8fe99ce301c9</RequestId>
</ResponseMetadata>
</ListInventorySupplyResponse>
C# Code:
string a = Convert.ToString(oInventorySupplyRes.ToXML());
XmlDocument oXdoc = new XmlDocument();
oXdoc.LoadXml(a);
XmlNodeList oInventorySupplyListxml = oXdoc.SelectNodes("//member");
foreach (XmlNode itmXml in oInventorySupplyListxml)
{
// var cond = itmXml.InnerXml.ToString();
var asinVal = itmXml.SelectSingleNode("ASIN").Value;
var TotalSupplyQuantityVal = itmXml.SelectSingleNode("TotalSupplyQuantity").Value;
}
ResultView : "Enumeration yielded no results" and count = 0;
Edit 1:
string a = Convert.ToString(oInventorySupplyRes.ToXML());
var status = oInventorySupplyResult.InventorySupplyList;
XmlDocument oXdoc = new XmlDocument();
var doc = XDocument.Parse(a);
var r = doc.Descendants("member")
.Select(member => new
{
ASIN = member.Element("ASIN").Value,
TotalSupplyQuantity = member.Element("TotalSupplyQuantity").Value
});
private string mStrXMLStk = Application.StartupPath + "\\Path.xml";
private System.Xml.XmlDocument mXDoc = new XmlDocument();
mXDoc.Load(mStrXMLStk);
XmlNode XNode = mXDoc.SelectSingleNode("/ListInventorySupplyResult/InventorySupplyList/member");
if (XNode != null)
{
int IntChildCount = XNode.ChildNodes.Count;
for (int IntI = 1; IntI <= IntChildCount ; IntI++)
{
string LocalName = XNode.ChildNodes[IntI].LocalName;
XmlNode Node = mXDoc.SelectSingleNode("/Response/" + LocalName);
// Store Value in Array assign value by "Node.InnerText"
}
}
Try This Code. Its Worked
try using this xpath
string xPath ="ListInventorySupplyResponse/ListInventorySupplyResult
/InventorySupplyList/member"
XmlNodeList oInventorySupplyListxml = oXdoc.SelectNodes(xpath);
when you do "//member", then, the code is trying to look for element named member from the root level, which is not present at the root level, rather it is nested beneath few layers.
I think this will help you..
string a = Convert.ToString(oInventorySupplyRes.ToXML());
XmlDocument oXdoc = new XmlDocument();
oXdoc.LoadXml(a);
XmlNodeList fromselectors;
XmlNodeList toselectors;
XmlElement root = oXdoc.DocumentElement;
fromselectors = root.SelectNodes("ListInventorySupplyResult/InventorySupplyList/member/ASIN");
toselectors = root.SelectNodes("ListInventorySupplyResult/InventorySupplyList/member/TotalSupplyQuantity");
foreach (XmlNode m in fromselectors)
{
you will have value in `m.InnerXml` use it whereever you want..
}
foreach (XmlNode n in toselectors)
{
you will have value in `n.InnerXml` use it whereever you want..
}
I have a problem with this XML. In our system we are using XML from DataSet (ds.GetXml()) and send it to our Silverlight application as a string. From there we read the XML with the following:
StringReader stream = new StringReader(XmlData);
XmlReader reader = XmlReader.Create(stream);
XDocument myDoc = new XDocument();
myDoc = XDocument.Load(reader);
The problem: Some times column names are changed, example: If a column name starts with a numeric number then it will convert it.
"_x0033_column" original column name was "3column"
Is it possible to get the original column name from the XML?
The XML
<NewDataSet>
<Table>
<CheckboxCol>0</CheckboxCol>
<Kunde>1</Kunde>
<Ort_x0020_Postfach />
<erfasst_x0020_von>MasterMind</erfasst_x0020_von>
<Buchhaltungsnummer>1</Buchhaltungsnummer>
<Kreditlimit>0.0000</Kreditlimit>
<_x0033_STT_Inaktiv>Nein</_x0033_STT_Inaktiv>
<_x0033_STT_Status>Interessent</_x0033_STT_Status>
<Zahlungsbedingungen>10 : 10 Tage Netto</Zahlungsbedingungen>
</Table>
<Table>
<CheckboxCol>0</CheckboxCol>
<Kunde>3</Kunde>
<Ort_x0020_Postfach />
<erfasst_x0020_von>MasterMind</erfasst_x0020_von>
<Buchhaltungsnummer>3</Buchhaltungsnummer>
<Kreditlimit>0.0000</Kreditlimit>
<_x0033_STT_Inaktiv>Nein</_x0033_STT_Inaktiv>
<_x0033_STT_Status>Kunde</_x0033_STT_Status>
<Zahlungsbedingungen>10 : 10 Tage Netto</Zahlungsbedingungen>
</Table>
<NewDataSet>
My current Code
public SLDataTable(string XmlData, Dictionary<string, string> ColumnDict)
{
ColumnDefination = ColumnDict;
foreach (var Item in ColumnDefination)
{
Columns.Add(new SLDataColumn() { ColumnName = Item.Key.ToString().Trim(), DataType = GetNullableType(GetColumnType(Item.Value.ToString())) });
}
StringReader stream = new StringReader(XmlData);
XmlReader reader = XmlReader.Create(stream);
XDocument myDoc = new XDocument();
myDoc = XDocument.Parse(XmlData);
if (myDoc != null && myDoc.Elements().Count() > 0 && myDoc.Element("NewDataSet").Elements().Count() > 0)
{
int columnCount = myDoc.Element("NewDataSet").Element("Table").Elements().Count();
int rowCount = myDoc.Element("NewDataSet").Elements().Count();
string ElmentColumnName = string.Empty;
foreach (XElement element in myDoc.Element("NewDataSet").Elements())
{
var row = new SLDataRow(this);
foreach (XElement ele in element.Elements())
{
ElmentColumnName = ele.Name.ToString().Replace("_x0020_", " ").Replace("_x0028_", " (").Replace("_x0029_", ") ");
row[ElmentColumnName] = ConvertValue(ElmentColumnName, ele.Value);
}
Rows.Add(row);
}
}
}