Populating combobox with XML attribute? - c#

How should I populate combobox with XML attribute. My XML file is:
<dataSources>
<dataSource id="1" name="support" dbtype="Oracle" dataSource="foo" initialCatalog="" userId="bar" password="x" />
</dataSources>
<services>
I need to populate 2 comboboxes with XML attribute names. I have the below code also but right now I am not getting the required output?
XmlDocument doc = new XmlDocument();
doc.Load("abc.xml");
XmlNodeList colorList = doc.SelectNodes("config/dataSources");
foreach (XmlNode dataSources in colorList)
{
comboBox1.Items.Add(dataSources.InnerXml);
}
foreach (XmlNode dataSources in colorList)
{
comboBox2.Items.Add(dataSources.InnerXml);
}

You want value of attribute name:
XmlDocument doc = new XmlDocument();
doc.Load("abc.xml");
XmlNodeList colorList = doc.SelectNodes("config/dataSources/dataSource");
foreach (XmlNode dataSources in colorList)
{
comboBox1.Items.Add(dataSources.Attributes["name"].Value.ToString());
}

Try this:
foreach (XmlNode dataSources in colorList)
{
foreach(XmlAttribute attribute in dataSources.Attributes)
{
comboBox1.Items.Add(attribute.Name); // add the attribute name to cb1
comboBox2.Items.Add(attribute.Value); // add the attribute value to cb2
}
}

Related

Empty Child and another child attribute vlaues

Hi All: Could you please tell me what is the mistake in gettting the child & child2 attribute values?
I'm getting the valu of the node attribute but not for the childs nodes.
Overall i need to get Name value from products, Visibile value from the element Visibilities, and Price value from elment Prices.
Code:
XmlDocument doc = new XmlDocument();
doc.Load("Prices.txt");
XmlNodeList nodes = doc.GetElementsByTagName("RetroPrintProduct");
foreach (XmlNode node in nodes)
{
Console.WriteLine("Name={0} ", node.Attributes["Name"].Value);
foreach (XmlNode child in node.SelectNodes("ProductVisibility "))
{
Console.WriteLine("Visible={0}", child.Attributes["Visible"].Value);
foreach (XmlNode child2 in child.SelectNodes("Prices"))
{
Console.WriteLine("Price={0}", child2.Attributes["Price"].Value);
}
}
}
XML file:
<Item>
<RetroPrintProduct Nino123="d89e280b-c8d5-4da2-87da-36e4a57e2867" Nino1="2022ProfileProducts.RetroPrintProduct" Sys_Index="UpdateOnly" DefaultIconName="RetroPrints_10x8x2_R_Metallic.png" DefaultOutputProfileName="Nino" DefaultOutputProfileTypeFullName="2022Profile" Name="Item Retro">
<ShippingMethodPrices Index="Replace" />
<Visibilities Index="Replace" />
</RetroPrintProduct>
<RetroPrintProduct Nino123="67d1577d-7baf-4b3f-a9fb-9d52404e45f4" Nino1="2022ProfileProducts.RetroPrintProduct" Sys_Index="UpdateOnly" DefaultIconName="RetroPrints_10x8x2_S_Normal.png" DefaultOutputProfileName="Nino" DefaultOutputProfileTypeFullName="2022Profile" Name="Item 2 Retro">
<ShippingMethodPrices Index="Replace" />
<Visibilities Index="Replace">
<ProductVisibility Nino123="cc0096e0-d964-4e45-93f7-9258ddee148d" Sys_GlobalUniqueId="cc0096e0-d964-4e45-93f7-9258ddee148d" Sys_ReplicationId="39f43856-a16f-4555-b519-ccf71b97ee58" Nino1="2022.ProductVisibility" Activated="True" Noprices="False" PhotoSource="EndUserPhotos" BackgroundColor="Default" Icon="" Image="" IsUnusableByLicense="False" MaxDate="2999-12-31" MinDate="1900-01-01" Name="" Object="Visible" Visible="True" ProductLibrary="" ReplicationId="39f43856-a16f-4555-b519-ccf71b97ee58" SysCode="">
<Prices Index="Replace">
<ProductPrice Nino123="4ca2658e-3e07-4636-b33f-d87fb021288a" Sys_GlobalUniqueId="4ca2658e-3e07-4636-b33f-d87fb021288a" Sys_ReplicationId="3e75b8f4-d1b6-41fe-be9e-d2858caf6eb9" Nino1="2022.ProductPrice" FixFee="0" ServiceFee="0" Mode="Replace" FromQuantity="1" Price="0.5" ProductPriceType="PerPageQuantity" ProductLibrary="" ReplicationId="3e75b8f4-d1b6-41fe-be9e-d2858caf6eb9" SysCode="" />
</Prices>
</ProductVisibility>
</Visibilities>
</RetroPrintProduct>
</Item>
It looks like you're missing some nesting when searching through the nodes. ProductVisibility is under Visibilites, not RetroPrintProduct, and Price is an attribute of ProductPrice, not Prices.
Something like this should do the trick (note that I named the nodes in code to match the xml names to make it easier to remember which child is which):
XmlDocument doc = new XmlDocument();
doc.Load(#"c:\temp\Prices.xml");
XmlNodeList retroPrintProducts = doc.GetElementsByTagName("RetroPrintProduct");
foreach (XmlNode retroPrintProduct in retroPrintProducts)
{
Console.WriteLine("Name={0} ", retroPrintProduct.Attributes["Name"].Value);
foreach (XmlNode visibility in retroPrintProduct.SelectNodes("Visibilities"))
{
foreach (XmlNode productVisibilty in visibility.SelectNodes("ProductVisibility"))
{
Console.WriteLine("Visible={0}", productVisibilty.Attributes["Visible"].Value);
foreach (XmlNode price in productVisibilty.SelectNodes("Prices"))
{
foreach (XmlNode productPrice in price.SelectNodes("ProductPrice"))
{
Console.WriteLine("Price={0}", productPrice.Attributes["Price"].Value);
}
}
}
}
}

Update to XML attribues list from datagrid

Morning:
Using the below method GetProductsPriceList() i read attributes of the selective nodes from the XML file and load it to the datagrid.
I edit the values of Visible & Price columns and save back to the XML File.
private ObservableCollection<Products> GetProductsPriceList()
{
productpricelist = new ObservableCollection<Products>();
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\xmltest\26112023.txt");
foreach (XmlElement pn in doc.SelectNodes("/Data/Products/*"))
{
var productlist = new Products
{
Mainproduct = pn.LocalName.ToString(),
Name = pn.GetAttribute("Name"),
Price = pn.SelectSingleNode(".//ProductPrice/#Price")?.Value,
Visible = pn.SelectSingleNode(".//ProductVisibility/#Visible")?.Value,
NameIcon = pn.GetAttribute("DefaultIconName")
};
productpricelist.Add(productlist);
}
return productpricelist;
}
My issue here, when i try to save to the xml file with datagrid view contents of Price & Visible attributes only one value is applied to all the attributes of Price & Visible .
Expected result: Each Price & Visible vlaues from datagrid should be applied to each product of the Price & Visible attributes.
During debug i can see the pp.Visible & pp.Price has the right contents i.e. the values entered in the datagrid.
I dont know what is wrong with my approcah with Foreach loop? How can i fix this? thanks
Price is an attribute of ProductPrice and
Visible is an attribute of ProductVisibility under Visibilities
private void Execute(object parm) //method to save back to the xml file price & visible attributes for each products
{
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\xmltest\26112023.txt");
foreach (Products pp in productpricelist)
{
foreach (XmlElement pn in doc.SelectNodes("/Data/Products/*"))
{
foreach (XmlNode visibility in pn.SelectNodes("Visibilities"))
{
foreach (XmlNode productVisibilty in visibility.SelectNodes("ProductVisibility"))
{
productVisibilty.Attributes["Visible"].InnerText = pp.Visible;
foreach (XmlNode price in productVisibilty.SelectNodes("Prices"))
{
foreach (XmlNode productPrice in price.SelectNodes("ProductPrice"))
{
productPrice.Attributes["Price"].InnerText = pp.Price;
}
}
}
}
}
}
doc.Save(#"C:\xmltest\26112023_.txt");
}
Sample XML File:
<?xml version="1.0" encoding="utf-8"?>
<Data>
<ShippingMethodsReferences />
<Products>
<ProductApple ID="77f9df03-7525-44d7-b08d-dcf106b44969" Sys_Type="Library.Domain.Products.ProductApple" Sys_ImportStrategy="UpdateOnly" DefaultIconName="Xerox_10x8x2_R_Sticker.png" Profile="Fruits" DefaultOutputProfileTypeFullName="Output" Name="(10x8)x2 H Rectangular">
<ShippingMethodPrices ImportStrategy="Replace" />
<Visibilities ImportStrategy="Replace">
<ProductVisibility ID="adfa5eca-3f58-4107-8738-5b9b1c0b666f" Sys_GlobalUniqueId="adfa5eca-3f58-4107-8738-5b9b1c0b666f" Sys_ReplicationId="ee46c28d-7b82-447d-a3a9-a67e0e4bbd5b" Sys_Type="ProductVisi" Activated="True" OverrideServerProductPrices="False" PhotoSource="EndUserPhotos" BackgroundColor="Default" Icon="" Image="" IsUnusableByLicense="False" MaxDate="2999-12-31" MinDate="1900-01-01" Name="" OrderableObjectVisibility="Visible" Visible="True" ReplicationId="ee46c28d-7b82-447d-a3a9-a67e0e4bbd5b">
<Prices ImportStrategy="Replace">
<ProductPrice ID="e558ceed-1e64-4540-8958-0203fea2b53b" Sys_GlobalUniqueId="e558ceed-1e64-4540-8958-0203fea2b53b" Sys_ReplicationId="2810c015-da9b-4aa9-ad43-ac7c02341b79" Sys_Type="Library.Domain.ProductPrice" FixFee="0" ServiceFee="0" Mode="Replace" FromQuantity="1" Price="0" ProductPriceType="PerPageQuantity" ReplicationId="2810c015-da9b-4aa9-ad43-ac7c02341b79" />
</Prices>
</ProductVisibility>
</Visibilities>
</ProductApple>
<ProductSolo ID="7c1302d8-8832-451b-be64-c5d048d0332f" Sys_Type="Library.Domain.Products.ProductApple" Sys_ImportStrategy="UpdateOnly" DefaultIconName="Xerox_10x8x2_R_Metallic.png" Profile="Fruits" DefaultOutputProfileTypeFullName="Output" Name="(10x8)x2 H Rectangular">
<ShippingMethodPrices ImportStrategy="Replace" />
<Visibilities ImportStrategy="Replace">
<ProductVisibility ID="078f6e6a-895c-4957-b808-2b38589ba4cd" Sys_GlobalUniqueId="078f6e6a-895c-4957-b808-2b38589ba4cd" Sys_ReplicationId="e0ca0706-0113-4479-ab47-59d2b14bf837" Sys_Type="ProductVisi" Activated="True" OverrideServerProductPrices="False" PhotoSource="EndUserPhotos" BackgroundColor="Default" Icon="" Image="" IsUnusableByLicense="False" MaxDate="2999-12-31" MinDate="1900-01-01" Name="" OrderableObjectVisibility="Visible" Visible="True" ReplicationId="e0ca0706-0113-4479-ab47-59d2b14bf837">
<Prices ImportStrategy="Replace">
<ProductPrice ID="0c14f953-9f75-4e24-9c38-245027107167" Sys_GlobalUniqueId="0c14f953-9f75-4e24-9c38-245027107167" Sys_ReplicationId="2d243d53-cd0c-4a92-adea-919a9bcb427d" Sys_Type="Library.Domain.ProductPrice" FixFee="0" ServiceFee="0" Mode="Replace" FromQuantity="1" Price="0" ProductPriceType="PerPageQuantity" ReplicationId="2d243d53-cd0c-4a92-adea-919a9bcb427d" />
</Prices>
</ProductVisibility>
</Visibilities>
</ProductSolo>
</Data>
</Products>
Before
foreach (XmlNode visibility in pn.SelectNodes("Visibilities"))
{
foreach (XmlNode productVisibilty in visibility.SelectNodes("ProductVisibility"))
{
productVisibilty.Attributes["Visible"].InnerText = pp.Visible;
foreach (XmlNode price in productVisibilty.SelectNodes("Prices"))
{
foreach (XmlNode productPrice in price.SelectNodes("ProductPrice"))
{
productPrice.Attributes["Price"].InnerText = pp.Price;
}
}
}
}
you have to check, if the product in pp equals the product in pn. If not you set Visible and Price Attribute of all Products selected with doc.SelectNodes("/Data/Products/*") instead of only the product in pp.
Without knowing the business model exactly, it's not possible for me to say exactly how to check if the product in pp is equal to the product in pn. It could maybe go like this, if Mainprduct is the primary key of the products:
if( pp.Mainproduct == pn.LocalName.ToString())
{
// TODO: Insert here the code from above
}

How to get "elements" in node

I trying to get "elements" from node and show in MessageBox
My XML: <Item Name="Test" Count="5"/>
Elements:
Name
Count
My Code:
XmlNodeList xmlNodes = xmlDocument.SelectNodes("Item");
foreach (XmlNode xmlNode in xmlNodes)
{
MessageBox.Show(xmlNode.InnerText);
}
But I do not know how to do this
You need to use Attributes. Check my solution
XmlNodeList xmlNodes = xmlDocument.SelectNodes("Item");
foreach (XmlNode xmlNode in xmlNodes)
{
foreach (XmlAttribute attr in xmlNodes.Attributes)
{
MessageBox.Show($"Attribute Name is {attr.Name} and Value is {attr.Value}");
}
}

Extracting nested nodes from xml file c#

I have this xml file:
<table head="Film">
<row>
<id>USD</id><jan>Jan</jan><feb>Feb</feb><mar>Mar</mar><apr>Apr</apr><maj>May</maj><jun>Jun</jun><jul>Jul</jul><aug>Aug</aug><sep>Sep</sep><okt>Oct</okt><nov>Nov</nov><dec>Dec</dec><sum>Year</sum>
</row>
<row>
<id>2018</id><jan>7629</jan><feb>6433</feb><mar>5573</mar><apr>3676</apr><maj>2545</maj><jun>2542</jun><jul>266</jul><aug>276</aug><sep>2690</sep><okt>371</okt><nov>5446</nov><dec>754</dec><sum>52731</sum>
</row>
I'm trying to extract the individual values for every month.
I've tried
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("model.xml");
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("table");
foreach (XmlNode node in nodeList) // for each <testcase> node
{
Console.WriteLine(node["row"].InnerText);
}
This gives an exception because node["row"] is empty.
Any ideas?
Firstly your XML is not valid. You need to have a </table> on there.
//In this example GetXml() just returns your XML
var doc = XDocument.Parse(GetXml());
var rows = doc.Descendants("table").Elements("row").ToList();
foreach(var element in rows[1].Elements()){
Console.WriteLine(element?.Value);
}
Now this is just a basic example based of your XML. You would likely want it to be more robust. You will notice I am showing you this with LINQ, I feel it's more readable than XmlDocument.
You need to loop through the child nodes to get your desired result as follow:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("model.xml");
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("table");
foreach (XmlNode node in nodeList) // for each <testcase> node
{
foreach (XmlNode row in node.ChildNodes)
{
foreach (XmlNode mon in row.ChildNodes)
{
}
}
}

how to parsing XML file

I have a file in that format
<?xml version="1.0" encoding="UTF-8"?>
<AMG>
<Include File="..."/> <!-- comment -->
<Include File="...."/> <!-- comment -->
<AMGmers Name="Auto">
<Array Type="move" Name="move_name"/>
</AMGmers>
<AMGmers Name="Black" Parent="Auto">
<Attr Type="Color" Name="auto_Params"/>
</AMGmers>
<!-- comment -->
</AMG>
I have to get all name from <AMGmers>, and I have to check availability Parent.
I was trying to do so
XmlDocument doc1 = new XmlDocument();
doc1.Load("test.xml");
XmlNodeList elemList1 = doc1.GetElementsByTagName("Name");
Please help me understand.
Since <AMG> is the root node and <AMGmers> tags are inside <AMG>, you can get all <AMGmers> tags using this syntax
XmlNodeList elemList1 = doc1.SelectNodes("AMG/AMGmers");
I assume you want to get the value of Name attribute from all <AMGmers> tags and check whether each <AMGmers> tag has Parent attribute, so this code should work
foreach (XmlNode node in elemList1)
{
if (node.Attributes["Name"] != null)
{
string name = node.Attributes["Name"].Value;
// do whatever you want with name
}
if (node.Attributes["Parent"] != null)
{
// logic when Parent attribute is present
// node.Attributes["Parent"].Value is the value of Parent attribute
}
else
{
// logic when Parent attribute isn't present
}
}
EDIT
If you want to get the <Array> nodes inside <AMGmers>, you can do so as below
foreach (XmlNode node in elemList1)
{
XmlNodeList arrayNodes = node.SelectNodes("Array");
foreach (XmlNode arrayNode in arrayNodes)
{
if (arrayNode.Attributes["Type"] != null)
{
// logic when Type attribute is present
// arrayNode.Attributes["Type"].Value is the value of Type attribute
}
}
}
EDIT 2
If you want to enumerate all nodes inside <AMGmers>, you can do so as below
foreach (XmlNode node in elemList1)
{
foreach (XmlNode childNode in node.ChildNodes)
{
// do whatever you want with childNode
}
}

Categories

Resources