How to move through different records in C# - c#

I made a form that basically displays information about different vendors from an XML file that I was given. The XML file is retrieved from a class that I created, called VendorsDB.cs. On my form, I have a Previous and Next button that I want to display the next vendor or the previous vendor (Vendor1, Vendor2...) but I have no idea what method to use. I know I have to use a loop but I'm not sure as to how to code the loop. I've just started programming with C# so I'm really lost. Any help would be greatly appreciated!

Your question is missing alot of information, but what im seeing is that you need to do some work with XML.
I suggest you look into Linq To XML which enabled you to query tags and attributes with query syntax.
A very simple query good look like this:
// Load the xml from the specified path
var xml = XDocument.Load(#"LocationOfXml");
// Query the first element with a "MyXmlTag" as name
var someAttribute = xml.Descendants().FirstOrDefault(x => x.Name == "MyXmlTag");
The query language is far richer than this simple query. Read up and im sure you'll be able to get it working asap.

Related

How to read an xaml file and get the data I want in C#

I want to read through a xaml file, and find all the lines with 'Annotation.AnnotationText' and get specific data from that line.For example, this line:
<prwab:Branch Condition="{x:Null}" sap2010:Annotation.AnnotationText="testing information " ContinuouslyExecute="False" CreatedBy="System Administrator" CreatedOn="2013-02-23T14:51:28.1555955-05:00" DisplayName="Failure" EnableValidationRule="False" sap:VirtualizedContainerService.HintSize="160,234" ID="ab91dec8-1976-491e-91eb-58e073a69d16" IsReportable="False" LastModifiedBy="System Administrator" LastModifiedOn="2013-02-23T14:51:28.1555955-05:00" MediaRecord="[MediaRecord]" SystemName="CollectDigitsActivity1 Failure6" Timeout="10000" Type="Voice">
I want find all the lines with 'AnnotationText' in my xaml file, and get information like text = 'testing information', id = 'ab91dec8-1976-491e-91eb-58e073a69d16' , created date and lastmodified date.
I have 0 knowledge in this area and I don't know where to start and which method should I use. Thanks for helping!
XAML is just a specific flavour of XML. You will need to use XML parsing to read the file into an object that you can process in this manner. I recommend Linq to XML for this (look at XDocument class to get started), specifically as finding values by XName using a specific namespace as you will need to for the "sap2010" namespace is very easy.
You can then easily parse and extract the information you are looking for using those classes.

Appending/Listing LINQ to XML data

I'm currently writing a function to save and read data to/from and XML document through
LINQ. Currently I can write the document just fine, but if I go to add data to an existing item, it simply adds a new item. My goal is to create an address book type system (yes I know there's 1000 out there, it's just a learning project for myself) and I've tried ini and basic text but it seems that XML is the best way to go short of using a local DB like sql. Currently I have:
XDocument doc = XDocument.Load(#"C:\TextXML.xml");
var data = new XElement("Entry",
new XElement("Name", textBox1.Text),
new XElement("Address", richTextBox2.Text),
new XElement("Comments", richTextBox1.Text));
doc.Element("Contacts").Add(data);
doc.Save(#"C:\TextXML.xml");
I searched SO and can't seem to find how to append/replace.
Now this saves everything properly, even when I add to the document, but if I want to update an entry I'm not sure how to without creating a new "Entry" nor am have I gotten the knack of removing one. (I'm somewhat new to C# still and self-taught so pardon anything obvious I've overlooked.)
My second issues revolves around loading the information into textboxes.
I'm able to load a list of Entry names into a listbox, but when I go to open the information from that entry I'm not sure how to properly get the nested info.
With the example above I'd need something similar to the following:
XDocument doc = XDocument.Load(#"C:\TextXML.xml");
boxName.Text = The name from the SelectedItem of the list box.
boxAddress.Text = The address child of the element named above etc.
Each method I've tried I wind up with a null reference exception, which tells me I'm not pointing to the right thing, but I'm not sure how to get to those things properly.
I've also tried creating a string and var of the SelectedItem from the list box to help with the naming, and using ToString methods, but still can't figure it out.
For replacing values, there are several functions you can use in XElement:
Value (property with a public setter)
SetValue()
SetElementValue()
SetAttributeValue()
ReplaceWith()
ReplaceNodes()
For example, if you wanted to replace the value in Name:
data.Element("Name").SetValue("NewValue");
or
data.Element("Name").Value = "NewValue";
For loading, once you have the XElement node you desire, then it's as simple as doing
xelement.Value
Or if it's an attribute:
xelement.Attribute("AttributeName").Value
Using your code as an example:
boxName.Text = doc.Element("Entry").Element("Name").Value;
Edit to address comment:
If I'm reading your comment right, you're wanting to extract the Name/Address/etc. data from all the nodes within the Contacts main node?
If so, then you would probably want something like this:
boxName.Text = string.Join(",", doc.Elements("Entry").Select(x => x.Element("Name").Value));
This will give you a single string that has all the names in all Entries separated by a comma. Just change "Name" to "Address" to do the same for addresses.
I'd suggest doing a search for Linq to XML for finding more information about how to use this parsing.

C# program to read, write, query xml

I would like to create a C# program to write, read, query xml file. I am very new to xml using C#. Can anyone please help me..
specifically i want to do this:
<streets>
<street1>
<house1 no=1 color=red/>
</street1>
<street2>
<house2 no=2 color=blue/>
</street2>
</streets>
I want to read this xml file and print all the houses and their properties.
I want to append to this xml file any new houses
I want to query where any specific house is located.
Can anyone please help me in this?
You can use LINQ. Please have a look at this article: http://www.codeproject.com/Articles/24376/LINQ-to-XML. Hope this help!
If you are interested in creating an application to create some data on 'House' and want to have the capabilities of editing/updating, adding and removing such data, and also want to store it in XML, then it is simple. Here I am considering that you are not very interested to know the exact metadata of the XML and the XML need not be following some predefined schema.
For such a requirement I worked sometime back and you may look at this for the same:
http://www.geekays.net/post/2011/03/24/XML-Data-Storage-and-XmlSerializer-The-easy-data-store.aspx

Retrieving metadata from xml files

I need to retrieve metadata from multiple xml files. The structure of the xml file is the following:
<songs>
<song_title> some title </song_title>
<classification> some classification </classification>
<song_text> some text </song_text>
<singer>
<sing> singer's name </sing>
<gender> gender </gender>
<bornYear> year </bornYear>
<livePlace> live place </livePlace>
<liveArea> live area </liveArea>
</singer>
</songs>
The user chooses the search criteria - live place or live area. Then he enters the name of the place or area, that he searches for. I need to find and display links to songs, which have in its metadata the place or area, that user has entered. I am using .NET 3.5
This answer is more of a pointer...
You can use LINQ to XML to accomplish this task.
What Is LINQ to XML?
LINQ to XML is a LINQ-enabled,
in-memory XML programming interface
that enables you to work with XML from
within the .NET Framework programming
languages.
LINQ to XML is like the Document
Object Model (DOM) in that it brings
the XML document into memory. You can
query and modify the document, and
after you modify it you can save it to
a file or serialize it and send it
over the Internet. However, LINQ to
XML differs from DOM: It provides a
new object model that is lighter
weight and easier to work with, and
that takes advantage of language
improvements in Visual C# 2008.
You can then search and manipulate any XML document element using LINQ query expressions like the following example:
IEnumerable<XElement> partNos =
from item in purchaseOrder.Descendants("Item")
where (int) item.Element("Quantity") *
(decimal) item.Element("USPrice") > 100
orderby (string)item.Element("PartNumber")
select item;
You can use XPathing to easily get whatever you want if you have an aversion to Linq
http://msdn.microsoft.com/en-us/library/ms256086%28VS.85%29.aspx
node.SelectNodes("Songs[/Singer/LivePlace='California']")
this would get all Songs nodes that have a singer node with a liveplace node with the value of California.

Validating and Extracting XML record by record into Database

Here's the deal. I have an XML document with a lot of records. Something like this:
print("<?xml version="1.0" encoding="utf-8" ?>
<Orders>
<Order>
<Phone>1254</Phone>
<City>City1</City>
<State>State</State>
</Order>
<Order>
<Phone>98764321</Phone>
<City>City2</City>
<State>State2</State>
</Order>
</Orders>");
There's also an XSD schema file. I would like to extract data from this file and insert these records into a database table. First of course I would like to validate each order record. For example if there are 5 orders in the file and 2 of them fail validation I would like to insert the 3 that passed validation into the db and left the other 2. There can be thousands of records in one xml file. What would be the best approach here. And how would the validation go for this since I need to discard the failed records and only use the ones that passed validation. At the moment I'm using XmlReaderSettings to validate the XML document records. Should I extract these records into another XML file or a Dataset or a custom object before I insert into a DB. I'm using .Net 3.5. Any code or link is welcome.
If the data maps fairly cleanly to an object model, you could try using xsd.exe to generate some classes from the .xsd, and process the classes into your DAL of choice. The problem is that if the volume is high (you mention thousands of records), you will most likely have a lot of round-trips.
Another option might be to pass the data "as is" through to the database and use SQL/XML to process the data in TSQL - presumably as a stored procedure that accepts a parameter of type xml (SQL Server 2005 etc).
I agree with idea that you should use an XmlReader, but I thought I'd try something a little different.
Basically, I am first validating the whole XDocument, then if there are errors, I enumerate through the orders and bin them as needed. It's not pretty, but maybe it'll give you some ideas.
XDocument doc = XDocument.Load("sample.xml");
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", "sample.xsd");
bool errors = false;
doc.Validate(schemas, (sender, e) =>
{
errors = true;
});
List<XElement> good = new List<XElement>();
List<XElement> bad = new List<XElement>();
var orders = doc.Descendants("Order");
if (errors)
{
foreach (var order in orders)
{
errors = false;
order.Validate(order.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>
{
errors = true;
});
if (errors)
bad.Add(order);
else
good.Add(order);
}
}
else
{
good = orders.ToList();
}
Instead of the lambda expressions, you could use a common function, but I just threw this together. Also, you could build two XDocuments instead of shoving the order elements into a list. I'm sure there are a ton of other problems here too, but maybe this will spark something.
You have a couple of options:
XmlDataDocument or XmlDocument. The downside to this approach is that the data will be cached in memory, which is bad if you have a lot of it. On the other hand, you get good in-memory querying facilities with DataSet. XmlDocument requires that you use XPath queries to work on the data, whereas XmlDataDocument gives you an experience more like the DataSet functionality.
XmlReader. This is a good, fast approach because the data isn't cached; you read it in a bit at a time as a stream. You move from one element to the next, and query information about that element in your application to decide what to do with it. This does mean that you maintain in your application's memory the tree level that you're at, but with a simple XML file structure like yours this should be very simple.
I recommend option 2 in your case. It should scale well in terms of memory usage, and should provide the simplest implementation for processing a file.
A lot of that depends on what "validation" means in your scenario. I assume, since you're using an .xsd, you are already validating that the data is syntactically correct.
So, validation probably means you'll be calling other services or procedures to determine if an order is valid?
You might want to look at Sql Server Integration Services. The XML Task in SSIS lets you do things like XPath queries, merging, likely anything and everything you'd need to do with that document. You could also use that do to all of your upfront validation with schema file too.
Marc's option of passing that data to a stored procedure might work in this scenario too, but SSIS (or, even DTS but you're going to give up too much related to XML to make it as nice of an option) will let you visually orchestrate all of this work. Plus, it'll make it easier for these things to run out of process so you should end up with a much more scalable solution.
By validation I mean validating each node. The nodes that have at least one error need to be inserted into a new xml document. Basically at the end I should have 2 xml documents. One containing the successful nodes and the other containing the failure nodes. Any way I can accomplish that? I'm using LINQ.

Categories

Resources