My XML Example:
<Table diffgr:id="Table17" msdata:rowOrder="16">
<IdRec>17</IdRec>
<FieldId>1213</FieldId>
<FieldDesc>Equipment</FieldDesc>
<FieldType>OptionBOX</FieldType>
<isReadOnly>false</isReadOnly>
<FieldValue>388</FieldValue>
<FieldTextValue>B - satisfactory</FieldTextValue>
<OptBox_Options>
<Options>
<myOPT FieldValue="387" FieldTextValue="A - good"/>
<myOPT FieldValue="388" FieldTextValue="B - satisfactory"/>
<myOPT FieldValue="389" FieldTextValue="C - needs change"/>
<myOPT FieldValue="390" FieldTextValue="D - deal"/>
</Options>
</OptBox_Options>
</Table>
My problem
The above xml data comes from a webservice. I have no problem with any field other than OptBox_Options which is a field I need to use to populate my spinner. Ergo I need to get the string from OptBox_Options->Options->myOpt(FieldTextValue) (for example: ).
How to access this data? What would be the best approach. If you can't give me a direct solution I would be satisfied with a link to noob friendly C# tutorial on the subject.
Isssue Resolved
I transformed my string to XML, then converted it to a dataset and just cycled through it... Code below :)
List<string> entries = new List<string>();
String rawXML = item.OptBox_Options;
StringReader stream = null;
XmlTextReader reader = null;
DataSet xmlDS = new DataSet();
stream = new StringReader(rawXML);
// Load the XmlTextReader from the stream
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
DataSet myOPTvalues = new DataSet();
myOPTvalues = xmlDS;
foreach (DataRow row in myOPTvalues.Tables[0].Rows)
{
var optItem = new PrevzemSpin();
optItem.FieldValue = row["FieldValue"].ToString();
if (optItem.FieldValue.Equals("")) optItem.FieldValue = null;
optItem.FieldTextValue = row["FieldTextValue"].ToString();
if (optItem.FieldTextValue.Equals("")) optItem.FieldTextValue = null;
entries.Add(optItem.FieldTextValue);
SpinnerValue.Tag = optItem.FieldValue;
}
Use xml parsing techniques such as XmlPullParser ,SAX parser or DOM parser.
XML Pull parser is the parser recommended in the developer's site of android Here is a tutorial for Pull parser .
I transformed my string to XML, then converted it to a dataset and just cycled through it... Code below :)
List<string> entries = new List<string>();
String rawXML = item.OptBox_Options;
StringReader stream = null;
XmlTextReader reader = null;
DataSet xmlDS = new DataSet();
stream = new StringReader(rawXML);
// Load the XmlTextReader from the stream
reader = new XmlTextReader(stream);
xmlDS.ReadXml(reader);
DataSet myOPTvalues = new DataSet();
myOPTvalues = xmlDS;
foreach (DataRow row in myOPTvalues.Tables[0].Rows)
{
var optItem = new PrevzemSpin();
optItem.FieldValue = row["FieldValue"].ToString();
if (optItem.FieldValue.Equals("")) optItem.FieldValue = null;
optItem.FieldTextValue = row["FieldTextValue"].ToString();
if (optItem.FieldTextValue.Equals("")) optItem.FieldTextValue = null;
entries.Add(optItem.FieldTextValue);
SpinnerValue.Tag = optItem.FieldValue;
}
Related
I am using c# and asp.net. Checkmarx scanner is giving issue HRA_CSHARP_Missing_XML_Validation. Missing XML Validation on this line
XmlReader xmlReader = (XmlReader)objCommand.ExecuteXmlReader();
Storedprocedure returning data in the xml format. Please help how to fix it? GetList is called on Page Load
private void GetList(int intTemplate_ID)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
string CONTROL_TYPE = "CHECKBOX";
XsltArgumentList args = new XsltArgumentList();
args.AddParam("control-type","",CONTROL_TYPE);
SqlConnection objConnect = new SqlConnection(strDBConnect);
SqlCommand objCommand = new SqlCommand( "usp_GetStates_xml", objConnect );
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.Parameters.Add ( new SqlParameter( "#Template_ID", SqlDbType.Int, 4));
objCommand.Parameters["#Template_ID"].Value = intTemplate_ID;
objConnect.Open();
XmlReader xmlReader = (XmlReader)objCommand.ExecuteXmlReader();
XPathDocument xmlDoc = new XPathDocument(xmlReader);
XslTransform xslDoc = new XslTransform();
xslDoc.Load(Server.MapPath("xslt/liststates.xslt"));
xslDoc.Transform(xmlDoc,args,sw,null);
this.pnlTransformation.Visible = true;
this.divTransformation.InnerHtml = sb.ToString();
xmlReader.Close();
}
Storedprocedure returns data in xml format
<Product>
<states state-id="11" is-assigned="N/A">Alabama</states>
<states state-id="12" is-assigned="N/A">Alaska</states>
</Product>
<?xml version="1.0" encoding="utf-8" ?>
<Title>
<subtitle>12,15,1,4 </subtitle>
</Title >
This is my xml structure and I need to split the value and add it to dropdownlist, but I'm getting whole value in dropdownlist, kindly provide me the solution and my code is
private void bindxml()
{
StreamReader str = new StreamReader(filepath);
using (DataSet ds = new DataSet())
{
ds.ReadXml(filepath);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "subtitle";
DropDownList1.DataBind();
}
}
DropDownList1.Items.AddRange(XElement.Load(filepath).Element("subtitle").Value
.Split(',').Select(x => new ListItem(x)).ToArray());
Load the XML, navigate to the "subtitle" element, split that value using the comma delimiter and then create a new ListItem for each element. Pass this collection, as an array, to the DropDownList AddRange method.
Use the below code:
string elements = string.Empty;
XmlDocument xml = new XmlDocument();
string xmlFilePath = Server.MapPath("XMLFile1.xml"); //File Name
xml.Load(xmlFilePath);
XmlNodeList companyList = xml.GetElementsByTagName("subtitle");
foreach (XmlNode node in companyList)
{
XmlElement companyElement = (XmlElement)node;
elements = companyElement.InnerText;
}
List<int> subIds = new List<int>();
if (elements!="")
{
subIds = elements.Split(',').Select(int.Parse).ToList();
}
ddlSub.DataSource = TagIds;
ddlSub.DataBind();
ddlSub.Items.Insert(0, new ListItem("--Select Subtitle--", "0"));
I'm busy with a application that extract data from Cisco CUCM to Datagridview with AXL/SOAP.
I get only the last record in the datagridview if I put the info to a combobox I get the compleet list.
The info what I extract with AXL is:
SEP0014A815DB0D
sk0000101
SEP0022555E7E26
AKijkindevegte
SEP0018BAC8C6C5
BT101139
This is my code:
byte[] soapBytes = Encoding.UTF8.GetBytes(soap);
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
HttpWebRequest httpRQ = (HttpWebRequest)HttpWebRequest.Create(string.Format(#"https://XXX.XXX.XXX.XXX:8443/axl/"));
httpRQ.ProtocolVersion = System.Net.HttpVersion.Version10;
httpRQ.Credentials = new NetworkCredential("user1", "password");//Callmanager gebruikersnaam / password
httpRQ.Method = "POST";
httpRQ.ContentType = "text/xml; charset=utf-8";
httpRQ.Accept = "text/xml";
httpRQ.Headers.Add("SOAPAction: 'CUCM:DB ver=" + version + "'");
httpRQ.ContentLength = soapBytes.Length;
//Send the xml soap to cucm
Stream stm = httpRQ.GetRequestStream();
stm.Write(soapBytes, 0, soapBytes.Length);
stm.Close();
//Build the xml response
XDocument responcedoc = new XDocument();
HttpWebResponse responce = httpRQ.GetResponse() as HttpWebResponse;
Stream responcedata = responce.GetResponseStream();
StreamReader responsereader = new StreamReader(responcedata);
Logging.Text += "\n---------|AXL Response|---------\n\n";
XDocument respdoc = XDocument.Load(responsereader);
Logging.Text += respdoc + "\n";
soap = null;
//fill in the combo
DevicePhone.Items.Clear();
foreach (XElement item in respdoc.Descendants("name"))
{
// DataSet ds = new DataSet();
//ds.ReadXml((string)item);
DevicePhone.Items.Add((string)item);
string ds;
strDevicePhone = ((string)item);
ds = ((string)item);
label3.Text = strDevicePhone;
try
{
DataTable jmn = new DataTable("respdoc");
dataGridView1.DataSource = jmn;
jmn.Columns.Add("name");
jmn.Columns.Add("userid");
jmn.Rows.Add((string)item);
return;
}
catch (Exception e)
{
//Interaction.MsgBox(ex.ToString());
}
Please Help
Whats do I wrong.
You're creating a new DataTable for each element and assigning this to your DataGridView.DataSource. Predictably, this will result in setting a source containing the last item.
Move the creation of your DataTable outside the loop and add the rows within it. Then assign your DataSource once after you've finished populating it.
var jmn = new DataTable("respdoc");
jmn.Columns.Add("name");
jmn.Columns.Add("userid");
foreach (var item in respdoc.Descendants("item"))
{
// ...
jmn.Rows.Add((string)item);
// ...
}
dataGridView1.DataSource = jmn;
I have a problem with the reading an xml, that was created saving the same schema that i used to read.
When I read a DataTable, for example Person, that has one row, the DataTable read the row but show me like all columns where null, when all columns are not null.
The code I use is the following
private DataSet LoadShema(string path)
{
string _archivoXsd = System.AppDomain.CurrentDomain.BaseDirectory +"Scheme.xsd";//HERE IS WHERE THE .XSD FILE IS
DataSet esquemaXSD = new DataSet();
string archivoXml = path;
FileStream FsXSD = new FileStream(_archivoXsd, FileMode.Open);
FileStream FsXML = new FileStream(archivoXml, FileMode.Open);
XmlTextReader xtrXSD = new XmlTextReader(FsXSD);
try
{
esquemaXSD.ReadXmlSchema(xtrXSD);
xtrXSD.Close();
FsXSD.Close();
XmlTextReader xtrXML = new XmlTextReader(FsXML);
esquemaXSD.ReadXml(xtrXML);
xtrXML.Close();
FsXML.Close();
}
catch
{
}
return esquemaXSD;
}
This is how I load the xml in the scheme, then another thing I do is assigning:
_dtPerson = new DataTable();
_dtPerson = esquemaXSD.Tables["Person"];
and for last, what I do is the following:
if (_dtPerson.Rows.Count == 1)
{
string name = Convert.ToString(_dtPerson.Rows[0]["Name"]);
}
and when i do the last code line, an exception that said "Can not convert DBNull object to other types".
I'm trying to read a simple webservice (REST) and populate a drop down box in my C# desktop application. I;m using .net 2.0
Following is my web service return xml
<sections type="array">
<section>
<name>Standing</name>
<created-at type="datetime">2011-10-23T23:17:54+05:30</created-at>
<updated-at type="datetime">2011-10-23T23:17:54+05:30</updated-at>
<id type="integer">1</id>
<status type="integer">1</status>
<service-charge type="float">0.0</service-charge>
</section>
<section>
<name>VIP</name>
<created-at type="datetime">2011-10-30T11:27:05+05:30</created-at>
<updated-at type="datetime">2011-10-30T11:27:05+05:30</updated-at>
<id type="integer">2</id>
<status type="integer">1</status>
<service-charge type="float">10.0</service-charge>
</section>
and in the following code I'm trying to convert the xml document to a data table
public DataTable getSections() {
String url = "http://<site_url>/sections.xml";
DataTable t = new DataTable();
HttpHandler handle = new HttpHandler();
StreamReader sr = handle.executeGET(url);
String xml = "";
while (sr.Peek() >= 0)
{
xml += sr.ReadLine();
}
XmlDataDocument doc = new XmlDataDocument();
doc.LoadXml(xml);
XmlReader xmlReader = new XmlNodeReader(doc);
DataSet ds = new DataSet();
ds.ReadXml(xmlReader);
t = ds.Tables[0];
return t;
}
and in the last segment I'm trying to bind it to my drop down box (cmbSections)
DataTable t = sec.getSections();
cmbSections.DataSource = t;
cmbSections.DisplayMember = "name";
cmbSections.ValueMember = "id";
But I'm getting the following error
Cannot bind to the new display member.
Parameter name: newDisplayMember
What am i missing here, please help, I'm new to C# world
Use extension method to support conversion of XElement to Datatable. You can add this method to any of your utility classes. Make sure the class is static.
public static class XElementExtensions
{
public static DataTable ToDataTable(this XElement element)
{
DataSet ds = new DataSet();
string rawXml = element.ToString();
ds.ReadXml(new StringReader(rawXml));
return ds.Tables[0];
}
public static DataTable ToDataTable(this IEnumerable<XElement> elements)
{
return ToDataTable(new XElement("Root", elements));
}
}
How to use
//Add logic to store xml data in file or string & read accordingly here.
string file = Server.MapPath("~/Data.xml");
XDocument document = XDocument.Load(file);
var query = from b in document.Elements("sections").Elements("section")
select b;
DataTable table = query.ToDataTable();
Simple way to convert XML to DataSet:
StringReader strr = new StringReader(strXML);
XmlTextReader xtr = new XmlTextReader(strr);
YourTypeDataSet dstest = new YourTypeDataSet();
dstest.ReadXml(xtr);
if (dstest.Tables.Count > 0) ...
for correct conversion, you replace your type DataSet in place of:
DataSet dstest = new DataSet();
;)
I got it working with the following code, but I'm not quit sure if this is the correct way to do it
(This parse the above same xml)
public DataTable getSections() {
String url = "http://<site_url>/sections.xml/sections.xml";
DataTable t = new DataTable();
t.Columns.Add("id", typeof(String));
t.Columns.Add("name", typeof(String));
HttpHandler handle = new HttpHandler();
StreamReader sr = handle.executeGET(url);
String xml = "";
List<String> id = new List<string>();
List<String> name = new List<string>();
while (sr.Peek() >= 0)
{
xml += sr.ReadLine();
}
XmlDataDocument doc = new XmlDataDocument();
doc.LoadXml(xml);
XmlReader xmlReader = new XmlNodeReader(doc);
while (xmlReader.Read()){
if (xmlReader.IsStartElement()) {
String b = xmlReader.Name;
switch (xmlReader.Name) {
case "sections":
break;
case "section":
break;
case "id":
if (xmlReader.Read())
{
id.Add(xmlReader.Value.Trim());
}
break;
case "name":
if (xmlReader.Read())
{
name.Add(xmlReader.Value.Trim());
}
break;
}
}
}
int counter = 0;
foreach (String i in id) {
DataRow r = t.NewRow();
r["id"] = i;
r["name"] = name[counter];
t.Rows.Add(r);
counter += 1;
}
return t;
}
Thanks for the comments :D
Your valuable comments are always welcome