How to get "elements" in node - c#

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}");
}
}

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);
}
}
}
}
}

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)
{
}
}
}

read child nodes xml

Here is my xml which i am trying to read.
<VacancyList xmlns="urn:abc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" generated="2016-04-20T11:42:47" xsi:schemaLocation="http://www.abc.in/dtd/vacancy-list.xsd">
<Vacancy id="1619993" date_start="2016-04-15" date_end="2016-04-22" reference_number="">
<Versions>
<Version language="nb">
<Title>Marketing Specialist</Title>
<TitleHeading/>
<Location>CXCXC</Location>
<Engagement/>
<DailyHours/>
<Region>
<County id="11">sds</County>
<County id="1">zxzx</County>
</Country>
</Region>
<Categories>
<Item type="position-type" id="3909">sER</Item>
<Item type="duration" id="contract">ss</Item>
<Item type="extent" id="fulltime">sd</Item>
<Item type="operating-time" id="day">s</Item>
</Categories>
</Version>
</Versions>
</Vacancy>
</VacancyList>
I want to read node location so wrote below code
XmlDocument xd = new XmlDocument();
xd.Load("https://abc.in/list.xml");
XmlNamespaceManager ns = new XmlNamespaceManager(xd.NameTable);
ns.AddNamespace("msbld", "urn:abc");
XmlNodeList nodelist = xd.SelectNodes("//msbld:VacancyList", ns);
if (nodelist != null)
foreach (XmlNode node in nodelist)
{
XmlNode nodelist1 = node.SelectSingleNode("Vacancy");
if (nodelist1 != null)
foreach (XmlNode node1 in nodelist1)
{
var k = node1.Attributes.GetNamedItem("Location").Value;
}
}
But i dont get anything in variable "node1". How to fix this?
Also is there any better solution for this?
Update1
i modified code but i only get node Title. cant get others inside Version node like Location.
if (nodelist != null)
foreach (XmlNode node in nodelist)
{
XmlNode nodelist1 = node.SelectSingleNode("//msbld:Vacancy/msbld:Versions",ns);
if (nodelist1 != null) {
XmlNode nodelist2 = nodelist1.SelectSingleNode("//msbld:Version", ns);
foreach (XmlNode node3Node in nodelist2)
{
var k = node3Node.Attributes.GetNamedItem("Location").Value;
}
}
}
xmlns="urn:abc" is a default namespace. Notice that descendant elements without prefix inherits ancestor's default namespace implicitly. You need to use the same prefix that references default namespace URI for acessing Vacancy and Location as well :
XmlNode nodelist1 = node.SelectSingleNode("msbld:Vacancy", ns);
Your updated code introduces an entirely different problem; / at the beginning of a path expression will always reference document element, unless you explicitly set the context to current active context by using . before /, for example :
XmlNode nodelist1 = node.SelectSingleNode(".//msbld:Vacancy/msbld:Versions",ns);
If you only need the Location element then you can do it like this:
var doc = XElement.Load("path/to/file");
var location = doc.Descendants
.FirstOrDefault(e => e.Name.LocalName == "Location"));

How to get the value for multiple subnode in xml?

Xml code:
<Report>
<ChartData>
<ListName>area</ListName>
<ViewName>Selecte List</ViewName>
<YAxisFields>
<YAxisField>
<Name>Scheduled Start Date/Time</Name>
<DataType>DateTime</DataType>
<Category>Year</Category>
</YAxisField>
</YAxisFields>
<XAxisFields>
<XAxisField>
<Name>Release Type</Name>
<DataType>String</DataType>
<Category>
</Category>
</XAxisField>
</XAxisFields>
</ChartConfig>
</Report>
I got the value for the subnode listname and viewname by using the
below code,
XmlDocument doc = new XmlDocument();
doc.Load("XmlFileName");
XmlNodeList node = doc.SelectNodes("Report/ChartData");
foreach (XmlNode xn in node)
{ xn["ListName"].InnerXml = chartname;
xn["ViewName"].InnerXml = SelectedList;
**xn["YAxisFields/YAxisField"].InnerXml = yaxisfield; //not working, need to get the value for this xml node,need help in this line dono how to proceed**
doc.Save("XmlFilename");
}
First i have tried with code like this instead of above code,in this
i need to create number of objects in order get the value for each
node so i tried by creating object for xmlnodelist then i used
foreach loop to get the value for each node but in this couldnt get
the value for YAxisFields/YAxisField because it also has parent node
as YAxisFields and subnode as YAxisField so there is only way to
create number of objects for xmlnode or is there any other way to do
this?
XmlDocument doc = new XmlDocument();
doc.Load("XmlFileName");
XmlNode Listnode = doc.SelectSingleNode("Report/ChartData/ListName");
XmlNode Viewnode = doc.SelectSingleNode("Report/ChartData/ViewName");
if (Listnode != null)
{
Listnode.InnerXml = chartname;
Viewnode.InnerXml = SelectedList; ;
doc.Save("XmlFileName");
Use Linq to XML XDocument, like this:
doc.Root.Descendants("ChartData").ToList().ForEach(node =>
{
node.Element("ListName").Value = chartname;
node.Element("ViewName").Value = SelectedList;
});

Populating combobox with XML attribute?

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
}
}

Categories

Resources