Hello I'm learning C# and I'm trying to show xml information from within User1.xml in a Textbox on the same form after it has been selected in the combobox.
I have managed to populate the combobox with the name tag using this code. (So that a username may be selected)
private void Form1_Load(object sender, EventArgs e)
{
XmlDocument sFor = new XmlDocument();
sFor.Load(Path.GetFullPath("User1.xml"));
XmlNodeList SearchList = sFor.SelectNodes("employee/user/name");
foreach (XmlNode Search in SearchList)
{
comboBox1.Items.Add(Search.InnerText);
}
}
The XML is formatted thusly
<employee>
<user>
<name>John Smith</name>
<department>PAI</department>
<manager>MD</manager>
<hours>full-time</hours>
<leave>940</leave>
</user>
</employee>
How would I (Using linq or xmlreader or otherwise) after selection in the Combobox, display the information in textBox2?
Thank you.
I did something similar with a DataGridView looking for a "City". The input field was Textbox1.Text. I hope this isnt overkill. The credit goes to the posters here at Stack for showing me how to do this! I pulled the specific data first, then load it to a List. lastly, made the List the data source for DGV. That might work for a combo box...yes?
<TaxTbl>
<TaxSite>
<Location>Axx</Location>
<Address>xxx</Address>
<City>aaa</City>
<State> st</State>
<Zip>xxx</Zip>
</TaxSite>
<TaxSite>
<Location>Bxxx</Location>
<Address>xxx</Address>
<City>xxx</City>
<State> st</State>
<Zip>xxx</Zip>
</TaxSite>
</TaxTbl>
var xdoc = XDocument.Load("C:\\Users\\Harley\\desktop\\outfile.xml");
var NewDoc = new XDocument(new XElement("TaxTbl",
from anEntry in xdoc.Element("TaxTbl").Elements("TaxSite")
where anEntry.Element("City").Value.Contains(textBox1.Text)
select anEntry));
var MyList =
(from bEntry in NewDoc.Descendants("TaxSite")
select new
{
Location = bEntry.Element("Location").Value,
Address = bEntry.Element("Address").Value,
City = bEntry.Element("City").Value,
State = bEntry.Element("State").Value,
Zip = bEntry.Element("Zip").Value
}).ToList();
cityDGV.DataSource = MyList.ToList();
If this can help you
XDocument doc = XDocument.Load(Path.GetFullPath("User1.xml"));
var rows = doc.Descendants("employee").Descendants("user").Select(el => new()
{
department = el.Element("department").Value,
manager = el.Element("manager").Value,
hours = el.Element("hours").Value,
leave = el.Element("leave").Value,
});
OR from DataSet like this
DataSet ds = new DataSet();
ds.ReadXmlSchema(new StreamReader("User1.xml"));
ds.ReadXml(new StreamReader("User1.xml"));
Related
This may be a duplicate, but I haven't been able to find a solution.
I have a ComboBox that is populated from an xml file. When I select an item in the ComboBox I want to populate a listBox with the "Special" elements from that same xml file.
xml:
<ClassID Barbarian="Barbarian">
<Name>Barbarian</Name>
<Alignment>NG CG NN CN NE CE</Alignment>
<Special>Fast Movement</Special>
<Special>Rage Power</Special>
</ClassID>
I can get the listBox to populate with ALL the "Special" elements, but I only want the ones for the specified class name (i.e. Barbarian attribute).
Code to populate listBox with ALL the "Special" elements, regardless of what ComboBox item is selected:
//Gets Specials from xml
public static List<string> GetSpecialsFromXml(string filename, string tagname)
{
List<string> Specials = new List<string>();
XmlDocument doc = new XmlDocument();
doc.Load(filename);
XmlNodeList specials = doc.GetElementsByTagName(tagname);
foreach(XmlNode special in specials)
{
Specials.Add(special.InnerText);
}
return Specials;
}
//Loads feats into feat list
public void LoadFeats()
{
List<string> Special = GetSpecialsFromXml(Gamepath, "Special");
FeatBox.Items.AddRange(Special.ToArray());
}
LoadFeats is called with the ComboBox SelectedItemChanged event.
I am still a noob when working with xml files.
Edit: TL;DR solution:
Changed public static List<string> GetSpecialsFromXml(string filename, string tagname) to public List<string> GetSpecialsFromXml(string filename, string tagname).
Added string Combo = ComboBox.Text; and string strXPath = $"ClassID[{Combo}='{Combo}']/Special"
Replaced XmlNodeList specials = doc.GetElementsByTagName(tagname);
with XmlNodeList specials = doc.SelectNodes( strXPath );
Instead of looking for "tagname", with doc.GetElemnetByTagName, use XPath in a SelectNodes() function call. XPath is to XML what SQL is to a database, and is very powerful.
Use an XPath statement like in a "SelectNodes()" call
string strXPath= "//ClassID[#Barbarian='Barbarian']/Special"
Replace your XmlNodeList specials = doc.GetElementsByTagName(tagname); with this
XmlNodeList specials = doc.SelectNodes( strXPath );
Then iterate away like you're already doing.
Good Luck with your project
Hi I have the following XML:
<EPICORTLOG>
<POS>
<ClientId>WkStn.90.1</ClientId>
<Id>POS.90.20140819.251.8279</Id>
<StartTime>2014-08-25T05:12:34</StartTime>
<Store>90</Store>
<SysDate>2014-08-19T00:00:00</SysDate>
<TillNo>1</TillNo>
<Time>2014-08-25T05:12:34</Time>
<Tran>1093</Tran>
<WkStn>1</WkStn>
<WORKSTATION>
<IsAutoLock>1</IsAutoLock>
</WORKSTATION>
<TRADE>
<ITEM>
<Class>102499</Class>
<Desc>NIKE RACER</Desc>
<FinalPrice>82.77</FinalPrice>
<Status>ACTV</Status>
<Style>EV0615</Style>
<Tag>1</Tag>
</ITEM>
</TRADE>
</POS>
</EPICORTLOG>
There are many POS nodes like above in the actual XML. I am trying to fetch the POS node with ID=POS.90.20140819.251.8279 and then the details of Item from that particular node. I have written the following query:
XDocument xdoc = XDocument.Load(XMLFile);
var item = from items in xdoc.Element("EPICORTLOG").Descendants("POS")
where items.Attribute("Id").Value == strSelectedPOSID
select new
{
desc=items.Element("ITEM").Attribute("Desc")
};
But it is not yielding any result for me. Here strSelectedPOSID=POS.90.20140819.251.8279. Please let me know where i am going wrong.
Id and Desc are not an Attributes. they are Elements so you should use
var item = from items in xdoc.Descendants("POS")
where (string)items.Element("Id") == strSelectedPOSID
select new
{
desc = (string)items.Element("ITEM").Element("Desc")
};
I got the value at last!! Following is what i used:
var item = from items in xdoc.Element("EPICORTLOG").Descendants("POS")
where (string)items.Element("Id") == strSelectedPOSID
select new
{
desc = items.Element("TRADE").Element("ITEM").Element("Desc").Value.ToString()
};
Thanks for the inputs.
I have a combobox with I am filling like this:
comboBox1.DataSource = items;
comboBox1.DisplayMember = "Item";
comboBox1.ValueMember = "Value";
Later I am attempting to get the value like this:
string value = comboBox1.SelectedValue.ToString();
I am expecting a string which contains "DFT". What I am getting, however is a string that contains "{ Item = Default Project, Value = DFT }".
Any idea how I can get just the DFT out of there?
Thanks
EDIT: Forgot that it wasn't apparent. Items is a List generated from an XDocument (Linq) using the descendants method. The XML looks like:
<Parent>
<Item>
<Name>Default project</Name>
<Value>DFT</Value>
</Item>
</Parent>
EDIT 2: This is my best guess as to the method I used to generate list (its at work and I don't remember it fully):
var items = (from i in xmlDoc.Descendants("item")
select new { Item = i.Element("Name").Value, Value = i.Element("Value").Value }).ToList();
I am trying to load an XML formatted string into my GUI using a TreeView control. However, the XML formated string is in proprietary layout.
The XML formatted string structure will look like this:
<Response>
<Data>
<Settings>
<Setting>
<SettingsXml>
<ScanJobs>
<ScanJobsData>
<Mailboxes>
<Name>user1#abc.com|DB1</Name>
<Value>true</Name>
</Mailboxes>
<Mailboxes>
<Name>user2#abc.com|DB1</Name>
<Value>true</Name>
</Mailboxes>
<Mailboxes>
<Name>user3#abc.com|DB2</Name>
<Value>true</Name>
</Mailboxes>
<Mailboxes>
<Name>user4#abc.com|DB2</Name>
<Value>true</Name>
</Mailboxes>
<Mailboxes>
<Name>user5#abc.com|DB3</Name>
<Value>true</Name>
</Mailboxes>
<Mailboxes>
<Name>user6#abc.com|DB3</Name>
<Value>true</Name>
</Mailboxes>
</ScanJobsData>
</ScanJobs>
</SettingsXml>
</Setting>
</Setting>
</Settings>
</Data>
</Response>
Where inside tags we have a and tags. tag represents the name of the mailbox appended with Database name to which that mail box belongs. For example- user1#abc.com is the name of the mailbox which is associated with Database having name as DB1. Now I am getting the above xml formatted data in a String not as a XML file.
I'd like the output to be structured in TreeView as follows :
+DB1
user1#abc.com
user2#abc.com
+DB2
user3#abc.com
user4#abc.com
+DB3
user5#abc.com
user6#abc.com
I've been searching the web for the past few hours, and none of the results have helped. Some have come close, but perhaps properties won't show up, or node's names won't display, etc.
I'm writing in c# in Visual Studio 2010. Thanks for the help!
Try this:
TreeView treeview = new TreeView();
// Get all the <Name> elements
XDocument doc = XDocument.Parse(xmlAsString);
var mailboxNames = doc.Element("Response").Element("Data").Element("Settings").Element("SettingsXml").Element("ScanJobs").Element("ScanJobsData").Elements("Mailboxes").Select(m => m.Element("Name"));
// Extract the email and db in each <Name> element
foreach (var name in mailboxNames)
{
var namesSplit = name.Value.Split('|');
var email = namesSplit[0];
var db = namesSplit[1];
// Create new db node if it not exists and add the email there
if (!treeview.Nodes.ContainsKey(db))
{
TreeNode[] emails = new TreeNode[] { new TreeNode(email) };
TreeNode node = new TreeNode(db, emails);
treeview.Nodes.Add(node);
}
// If db node already exists, add email to currently existing node
else
{
treeview.Nodes[db].Nodes.Add(email);
}
}
This query will return you sequence of DB TreeNodes with mail nodes already added to them:
XDocument xdoc = XDocument.Load(path_to_xml);
// or XDocument.Parse(xml_string);
var nodes = from m in xdoc.Descendants("Mailboxes")
let name = m.Element("Name").Value.Split('|')
select new {
Mail = name[0],
Db = name[1]
} into md
group md by md.Db into g
select new TreeNode(g.Key,
g.Select(x => new TreeNode(x.Mail)).ToArray());
Then simply
treeView.Nodes.AddRange(nodes.ToArray());
Ihave an xml file sample.xml
<?xml version="1.0" standalone="yes"?>
<DataSchema xmlns="http://tempuri.org/DataSchema.xsd">
<ManagedObject>
<Label>sam</Label>
<Owner>00000000-0000-0000-0000-000000000000</Owner>
<ClassID>00000000-0000-0000-0000-000000000008</ClassID>
<DefaultApp>00000000-0000-0000-0000-000000000000</DefaultApp>
<Name>rvi</Name>
<version>9.6</version>
</ManagedObject>
</DataSchema>
i need to display 9.6 (9.6) from above xml file to the listview.I started a new windowform application. i added listview named "_listview" put its view as a "detail" mode.I added a column
there named _version
Can you give me the code to display version number in the listview column
if your XML file will have always this structre you can use simply:
string version = "";
int n = 0;
using (DataSet ds = new DataSet())
{
ds.ReadXml(#"sample.xml");
if(ds.Tables.Contains("ManagedObject")
&& ds.Tables["ManagedObject"].Rows.Count > n)
{
ver = ds.Tables["ManagedObject"].Rows[n]["version"].ToString();
}
}
to get the n-th ManagedObject version.
in your case you have only 1, so n = 0.
if you want to add "version" as an item that will appear in the first column of the listview:
listView1.Items.Add(version);
if "version" is to be added to an existing item in a secondary column use:
listview1.Items[n].SubItems.Add(version);
you can look here for further details.
this will also work fine
XmlDocument doc = new XmlDocument();
doc.Load(#"F:\xml\sample.xml");
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("sam", "http://tempuri.org/DataSchema.xsd");
XmlNode node = doc.SelectSingleNode(
"/sam:DataSchema/sam:ManagedObject/sam:version", nsmgr);
string version = node == null ? null : node.InnerText;
_listview.Items.Add(version);