Why duplicate code?
I read on a rampage in the xml data! and installing a toolstripmenu! but for some reason every so often put into the xml amennyi item is in! Why?
here is the code:
try
{
XmlDocument xml = new XmlDocument();
xml.Load("allomasok.xml");
XmlNodeList xnList = xml.SelectNodes("/radiok/allomas");
mennyi =int.Parse(xnList.Count.ToString());
foreach (XmlNode xn in xnList)
{
string radioNEV = xn["neve"].InnerText;
string radioURL = xn["url"].InnerText;
//int i = mennyi;
ToolStripMenuItem[] items = new ToolStripMenuItem[mennyi];
for (int i = 0; i < items.Length; i++)
{
items[i] = new ToolStripMenuItem();
items[i].Name = "mentett" + i.ToString();
items[i].Tag = radioURL;
items[i].Text = radioNEV;
items[i].Click += new EventHandler(MenuItemClickHandler);
}
sajátokToolStripMenuItem.DropDownItems.AddRange(items);
}
}
catch
{
MessageBox.Show("Hiba", "NetRadioPlayer");
}
finally
{
MessageBox.Show("Ennyi mentett állomás van: " + mennyi);
}
Thanks.
You have too many loops, I think. Try this:
try
{
XmlDocument xml = new XmlDocument();
xml.Load("allomasok.xml");
XmlNodeList xnList = xml.SelectNodes("/radiok/allomas");
ToolStripMenuItem mi;
int i;
foreach (XmlNode xn in xnList)
{
string radioNEV = xn["neve"].InnerText;
string radioURL = xn["url"].InnerText;
mi = new ToolStripMenuItem();
mi.Name = "mentett" + i++.ToString();
mi.Tag = radioURL;
mi.Text = radioNEV;
mi.Click += new EventHandler(MenuItemClickHandler);
sajátokToolStripMenuItem.DropDownItems.Add(mi);
}
}
catch
{
MessageBox.Show("Hiba", "NetRadioPlayer");
}
finally
{
MessageBox.Show("Ennyi mentett állomás van: " + mennyi);
}
If that doesn't help I'm sorry, I don't understand the question.
Related
I have data in the following format:
https://www.dropbox.com/s/osu4w634lnoy2pw/2.xml
While trying to parse I want all the field elements also. I am able to get all the elements under table but not under field. Could somebody please help me?
My code is as follows:
XmlDocument doc = new XmlDocument();
doc.Load(#maploc);
XmlNodeList nodes = doc.DocumentElement.SelectNodes("/schema/table");
foreach (XmlNode node in nodes)
{
attribute1 = "";
attribute2 = "";
attribute3 = "";
try
{
attribute1 = node.Attributes["name"].Value;
attribute2 = node.SelectSingleNode("tabledefault").InnerText;
attribute3 = node.SelectSingleNode("invoke").InnerText;
}
catch(Exception ex)
{
//Nothing
}
if (node.HasChildNodes)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
foreach (XmlNode nodei in node.ChildNodes[i])
{
attribute4 = "";
attribute5 = "";
attribute6 = "";
try
{
attribute4 = node.Attributes["name"].Value;
attribute5 = node.SelectSingleNode("invoke").InnerText;
attribute6 = node.SelectSingleNode("dtype").InnerText;
catch (Exception ex)
{
//Nothing
}
}
}
}
Thanks...
Your error is :
for (int i = 0; i < node.ChildNodes.Count; i++)
{
foreach (XmlNode nodei in node.ChildNodes[i])
{
You are iterating over the nodes that are the children of the current child (you are going one level too deep). This is because an XmlNode is an Enumerable over its Children.
A single foreach loop is needed :
foreach (XmlNode nodei in node.ChildNodes)
{
I'm updating an xml file by this code,
public static void UpdateDesignCfg(string ChildName, string[,] AttribWithValue)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load("DesignCfg.xml");
XmlElement formData = (XmlElement)doc.SelectSingleNode("//" + ChildName);
if (formData != null)
{
for (int i = 0; i < AttribWithValue.GetLength(0); i++)
{
formData.SetAttribute(AttribWithValue[i, 0], AttribWithValue[i, 1]);
}
}
doc.Save("DesignCfg.xml");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
but I've often get this error ( not every time)
the process cannot access the file because it is being used by another process
so, Is there any way to " Release " the file after every change ?
UPDATE
The file is accessed from another place and is not closed. Use the same Load method in the other place.
I solved my problem, thanks so much #Ulugbek Umirov for help, the problem was on my ReadXmlFile Method, it was like this :
public static Color GetColor(string ChildName, string Attribute)
{
Color clr = new Color(); string v = "";
XmlTextReader reader = new XmlTextReader("DesignCfg.xml");
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
foreach (XmlNode chldNode in node.ChildNodes)
{
if (chldNode.Name == ChildName)
v = chldNode.Attributes["" + Attribute + ""].Value;
}
clr = System.Drawing.ColorTranslator.FromHtml(v);
return clr;
}
and the new one is :
public static Color GetColor(string ChildName, string Attribute)
{
Color clr = new Color();
string v = "";
XmlDocument doc = new XmlDocument();
doc.Load("DesignCfg.xml");
XmlElement formData = (XmlElement)doc.SelectSingleNode("//" + ChildName);
if (formData != null)
v = formData.GetAttribute(Attribute);
clr = System.Drawing.ColorTranslator.FromHtml(v);
return clr;
}
Thanks all for help :)
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 this XML
<?xml version="1.0" encoding="UTF-8"?>
<nfeProc xmlns="http://www.portalfiscal.inf.br/nfe" versao="2.00">-<NFe>-<infNFe versao="2.00" Id="NFe35130649196462000115550010000036141000025758">
<ide>
<natOp>DEVOL. ARMAZENAGEM</natOp>
</ide>
<total>
<ICMSTot>
<vNF>43778.00</vNF>
</ICMSTot>
</total>
I read with this C# code :
private void leerarquivoN(string caminx)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(caminx);
XmlNodeList ml = xmlDoc.GetElementsByTagName("*");
XmlNode primer = xmlDoc.DocumentElement;
tipo_arq = primer.Name;
if (xmlDoc.DocumentElement.Name == "nfeProc")
{ foreach (XmlNode xn in ml)
{
if (xn.Name == "infNFe")
{
chave_nota = xn.Attributes["Id"].Value;
versao = xn.Attributes["versao"].Value;
lblChaveNota.Text = chave_nota; lblversao.Text = versao;
}
}
XmlNodeList xnList = xmlDoc.GetElementsByTagName("ide");
foreach (XmlNode xn in xnList)
{
if (xn.Name == "ide")
{
if (xn["nNF"] != null)
{ nnota = (xn["nNF"]).InnerText; label8.Text = nnota; }
if (xn["dEmi"] != null)
{ ndata = (xn["dEmi"]).InnerText; lblData.Text = ndata;}
if (xn["natOP"] != null)
{ natop = (xn["natOP"]).InnerText; lblNAtop.Text = natop ; }
}
}
XmlNodeList xnList2 = xmlDoc.GetElementsByTagName("emit");
foreach (XmlNode xn in xnList2)
{
{ if (xn["CNPJ"] != null)
{ ncnpj = (xn["CNPJ"]).InnerText; lblCNPJ.Text = ncnpj; }
}
}
XmlNodeList xnList3 = xmlDoc.GetElementsByTagName("total");
foreach (XmlNode xn in xnList3)
{
{
if (xn["vNF"] != null)
{ ntotal = (xn["vNF"]).InnerText; lblvNF.Text = ntotal ; }
}
}
}
I can not read VNF and natOP , what i m doing wrong???
Thanks
The code you are using just gets the main nodes. To get the children associated with each node (natOp and vNF), you have to rely on a different code (MSDN reference). Sample for natOp (inside the xnList for loop):
if (xn.HasChildNodes)
{
for (int i=0; i<xn.ChildNodes.Count; i++)
{
//xn.ChildNodes[i].InnerText -> what you are after
}
}
I am trying to loop through an Xml file and display the value for account in a message.
XmlNodeList nodeList = testDoc.SelectNodes("/details/row/var");
foreach (XmlNode no in nodeList)
{
XmlNode node = testDoc.SelectSingleNode("/details/row/var[#name='account']");
test.actual = node.Attributes["value"].Value;
MessageBox.Show(test.account);
}
The message box is currently displaying the first record repeatidly, how can I get to the next record?
Thanks for your input in advance.
You are repeatedly assigning node with the same element from testDoc. It is not clear what test.account is (perhaps a mistype for test.actual)?
no is the variable which will iterate the contents of nodeList - I imagine you intended to use that.
EDIT following edit of OP
Now you've shown us what nodeList is, I suspect you want to do something like this instead :
XmlNodeList nodeList = testDoc.SelectNodes("/details/row/var[#name='account']");
foreach (XmlNode no in nodeList)
{
test.actual = no.Attributes["value"].Value;
...
XmlDocument doc = new XmlDocument();
doc.Load("d:\\test.xml");
XmlNodeList node = doc.GetElementsByTagName("w:r");
foreach (XmlNode xn in node)
{
try
{
if (xn["w:t"].InnerText != null)
{
if (xn["w:t"].InnerText == "#")
{
string placeHolder = xn["w:t"].InnerText;
foreach (XmlNode a in node)
{
if (a["w:t"].InnerText != "#")
{
string placeHolder1 = a["w:t"].InnerText;
}
}
}
}
}
catch (Exception e)
{
Console.Write(e);
}
}
Here is the sample for parent node value to get information of the child nodes.here i am using the ReportItems ParentNode and Print only image child nodes.
xmldoc.Load(rdlFile);
StringBuilder sb=new StringBuilder();
XmlNode node = xmldoc.GetElementsByTagName("ReportItems")[0];
XmlNodeList list = node.ChildNodes;
atributes=new string[node.ChildNodes.Count];
int l = 0;
for (int j = 0; j < node.ChildNodes.Count; j++)
{
if (list[j].Name == "Image")
{
XmlAttributeCollection att = list[j].Attributes;
atributes[l] = att[0].Value.ToUpper();
}
l++;
}
for (int i = 0; i < node.ChildNodes.Count; i++)
{
if (searchText.Text.ToUpper() == atributes[i])
{
XmlNodeList lastlist = node.ChildNodes;
XmlNodeList endlist = lastlist[i].ChildNodes;
for (int k = 0; k < endlist.Count; k++)
{
sb.Append(endlist[k].Name+" - "+ endlist[k].InnerText);
sb.Append("\n"+"\n");
}
}
}
let me know if you have doubt..
Try this,
XmlDocument xdoc = new XDocument();
xdoc.Load("*/File/*");
string xmlcontents = xdoc.InnerXml;
var xpath = "(/details/row/var[#name='account'])";
XmlNodeList lists = xdoc.DocumentElement.SelectNodes(xpath);
foreach (XmlNode _node in lists)
{
string _nodeValue = _node.InnerText;
MessageBox.Show(_nodeValue);
}
Try the following:
//Create an xml reader;
XmlDocument _xmlDocument = new XmlDocument();
_xmlDocument.Load(/*File Name here*/);
//Select the element with in the xml you wish to extract;
XmlNodeList _nodeList = _xmlDocument.SelectNodes("/details/row/var[#name='account']");
//Display the values in the node list to the screen;
foreach (XmlNode _node in _nodeList)
{
String _nodeValue = _node.InnerText.ToString();
MessageBox.Show(_nodeValue.ToString());
}
I'm not 100% sure, but you may need to use recursion. If not, it should just look like this:
XmlDocument doc = //etc..
foreach(XmlNode node in doc.ChildNodes)
{
if(node.Name == "account")
{
MessageBox.Show(node.Value);
}
}
You shouldn't spend time with reading the xml node by node. Try Deserialization: