Search Results

Search found 19804 results on 793 pages for 'linq to xml'.

Page 5/793 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How often are comments used in XML documents?

    - by Jeffrey Sweeney
    I'm currently developing a web-based XML managing program for a client (though I may 'market' it for future clients). Currently, it reads an XML document, converts it into manageable Javascript objects, and ultimately spits out indented, easy to read XML code. Edit: The program would be used by clients that don't feel like learning XML to add items or tags, but I (or another XML developer) may use the raw data for quick changes without using an editor. I feel like fundamentally, its ready for release, but I'm wondering if I should go the extra mile and allow support for remembering (and perhaps making) comments before generating the resulting XML. Considering that these XML files will probably never be read without a program interpreting it, should I really bother adding support for comments? I'll probably be the only one looking at raw files, and I usually don't use comments for XML anyway. So, are comments common/important in most XML documents?

    Read the article

  • perl xml parser get xml content within xml

    - by user391986
    How can I use XMLParser to get the item-@url, item-@replace and item-"value inside" for the content as a string of the node where item-@cone="one"? <cstep> <item cone="one" url="http://google.com/{ccc}/cthree" replace="{ccc}"> <itemsub conesub="conesub"> <itemsubsub conesubsub="conesubsub" /> </itemsub> </item> <item cone="two" url="http://google.com/{ccc}/cthree" replace="{ccc}"> <itemsub conesub="conesub"> <itemsubsub conesubsub="conesubsub" /> </itemsub> </item> </cstep>

    Read the article

  • Transactions in LINQ to SQL applications

    - by nikolaosk
    In this post I would like to talk about LINQ to SQL and transactions.When I have a LINQ to SQL class I always get asked this question, "How does LINQ treat Transactions?". When we use the DeleteOnSubmit() method or the InsertOnSubmit() method, all of those commands at some point are translated into T-SQL commands and then are executed against the database. All of those commands live in transactions and they follow the basic rules of transaction processing. They do succeed together or fail together...(read more)

    Read the article

  • Parallel LINQ - PLINQ

    - by nmarun
    Turns out now with .net 4.0 we can run a query like a multi-threaded application. Say you want to query a collection of objects and return only those that meet certain conditions. Until now, we basically had one ‘control’ that iterated over all the objects in the collection, checked the condition on each object and returned if it passed. We obviously agree that if we can ‘break’ this task into smaller ones, assign each task to a different ‘control’ and ask all the controls to do their job - in-parallel, the time taken the finish the entire task will be much lower. Welcome to PLINQ. Let’s take some examples. I have the following method that uses our good ol’ LINQ. 1: private static void Linq(int lowerLimit, int upperLimit) 2: { 3: // populate an array with int values from lowerLimit to the upperLimit 4: var source = Enumerable.Range(lowerLimit, upperLimit); 5:  6: // Start a timer 7: Stopwatch stopwatch = new Stopwatch(); 8: stopwatch.Start(); 9:  10: // set the expectation => build the expression tree 11: var evenNumbers =   from num in source 12: where IsDivisibleBy(num, 2) 13: select num; 14: 15: // iterate over and print the returned items 16: foreach (var number in evenNumbers) 17: { 18: Console.WriteLine(string.Format("** {0}", number)); 19: } 20:  21: stopwatch.Stop(); 22:  23: // check the metrics 24: Console.WriteLine(String.Format("Elapsed {0}ms", stopwatch.ElapsedMilliseconds)); 25: } I’ve added comments for the major steps, but the only thing I want to talk about here is the IsDivisibleBy() method. I know I could have just included the logic directly in the where clause. I called a method to add ‘delay’ to the execution of the query - to simulate a loooooooooong operation (will be easier to compare the results). 1: private static bool IsDivisibleBy(int number, int divisor) 2: { 3: // iterate over some database query 4: // to add time to the execution of this method; 5: // the TableB has around 10 records 6: for (int i = 0; i < 10; i++) 7: { 8: DataClasses1DataContext dataContext = new DataClasses1DataContext(); 9: var query = from b in dataContext.TableBs select b; 10: 11: foreach (var row in query) 12: { 13: // Do NOTHING (wish my job was like this) 14: } 15: } 16:  17: return number % divisor == 0; 18: } Now, let’s look at how to modify this to PLINQ. 1: private static void Plinq(int lowerLimit, int upperLimit) 2: { 3: // populate an array with int values from lowerLimit to the upperLimit 4: var source = Enumerable.Range(lowerLimit, upperLimit); 5:  6: // Start a timer 7: Stopwatch stopwatch = new Stopwatch(); 8: stopwatch.Start(); 9:  10: // set the expectation => build the expression tree 11: var evenNumbers = from num in source.AsParallel() 12: where IsDivisibleBy(num, 2) 13: select num; 14:  15: // iterate over and print the returned items 16: foreach (var number in evenNumbers) 17: { 18: Console.WriteLine(string.Format("** {0}", number)); 19: } 20:  21: stopwatch.Stop(); 22:  23: // check the metrics 24: Console.WriteLine(String.Format("Elapsed {0}ms", stopwatch.ElapsedMilliseconds)); 25: } That’s it, this is now in PLINQ format. Oh and if you haven’t found the difference, look line 11 a little more closely. You’ll see an extension method ‘AsParallel()’ added to the ‘source’ variable. Couldn’t be more simpler right? So this is going to improve the performance for us. Let’s test it. So in my Main method of the Console application that I’m working on, I make a call to both. 1: static void Main(string[] args) 2: { 3: // set lower and upper limits 4: int lowerLimit = 1; 5: int upperLimit = 20; 6: // call the methods 7: Console.WriteLine("Calling Linq() method"); 8: Linq(lowerLimit, upperLimit); 9: 10: Console.WriteLine(); 11: Console.WriteLine("Calling Plinq() method"); 12: Plinq(lowerLimit, upperLimit); 13:  14: Console.ReadLine(); // just so I get enough time to read the output 15: } YMMV, but here are the results that I got:    It’s quite obvious from the above results that the Plinq() method is taking considerably less time than the Linq() version. I’m sure you’ve already noticed that the output of the Plinq() method is not in order. That’s because, each of the ‘control’s we sent to fetch the results, reported with values as and when they obtained them. This is something about parallel LINQ that one needs to remember – the collection cannot be guaranteed to be undisturbed. This could be counted as a negative about PLINQ (emphasize ‘could’). Nevertheless, if we want the collection to be sorted, we can use a SortedSet (.net 4.0) or build our own custom ‘sorter’. Either way we go, there’s a good chance we’ll end up with a better performance using PLINQ. And there’s another negative of PLINQ (depending on how you see it). This is regarding the CPU cycles. See the usage for Linq() method (used ResourceMonitor): I have dual CPU’s and see the height of the peak in the bottom two blocks and now compare to what happens when I run the Plinq() method. The difference is obvious. Higher usage, but for a shorter duration (width of the peak). Both these points make sense in both cases. Linq() runs for a longer time, but uses less resources whereas Plinq() runs for a shorter time and consumes more resources. Even after knowing all these, I’m still inclined towards PLINQ. PLINQ rocks! (no hard feelings LINQ)

    Read the article

  • Retrieving data using stored procedures with LINQ to SQL in an ASP.Net application

    - by nikolaosk
    In this post I would like to present a step by step example on how to use stored procedures with LINQ to SQL. Many people will wonder why I am bothering talking about LINQ to SQL so much. First of all I give a lot of seminars where people want to learn LINQ to SQL.A lot of people like and use LINQ to SQL in their projects. There are a lot of people right now who use it extensively. In this post I will use two stored procedures that return data from the database. If you want to check out how to use...(read more)

    Read the article

  • Select,Insert,Update and Delete data with LINQ to SQL in an ASP.Net application

    - by nikolaosk
    As you might have guessed I am continuing my LINQ to SQL posts. I am teaching a course right now on ADO.Net 3.5 (LINQ & EF) and I know a lot of people who have learned through my blog and my style of writing. I am going to use a step by step example to demonstrate how to select,update,insert,delete data through LINQ to SQL into the database. If you want to have a look on how to return data from a database with LINQ to SQL and stored procedures click here . If you want to have a look on how to...(read more)

    Read the article

  • Compiled Linq & String.Contains

    - by sharru
    i'm using linq-to-sql and i'm use complied linq for better performance. I have a users table with a INT field called "LookingFor" that can have the following values.1,2,3,12,123,13,23. I wrote a query to return the users based on the "lookingFor" column i want to return all users that contains the "lookingFor" value (not only those equal to it). In example if user.LookingFor = 12 , and query paramter is 1 this user should be selected. private static Func<NeDataContext, int, IQueryable<int>> MainSearchQuery = CompiledQuery.Compile((NeDataContext db, int lookingFor) => (from u in db.Users where (lookingFor == -1 ? true : u.LookingFor.ToString().Contains(lookingFor) select u.username); This WORKS on non complied linq but throws error when using complied. How do i fix it to work using complied linq? I get this error: Only arguments that can be evaluated on the client are supported for the String.Contains method.

    Read the article

  • MVC using LINQ? - Can't return anonymous types

    - by BlueRaja
    I'd like to implement MVC while using LINQ (specifically, LINQ-to-entities). The way I would do this is have the Controller generate (or call something which generates) the result-set using LINQ, then return that to the View to display the data. The problem is, if I do: return (from o in myTable select o); All the columns are read from the database, even the ones (potentially dozens) I don't want. And - more importantly - I can't do something like this: return (from o in myTable select new { o.column }); because there is no way to make anonymous types type-safe! I know for sure there is no nice, clean way of doing this in 3.5 (this is not clean...), but what about 4.0? Is there anything planned, or even proposed? Without something like duck-typing-for-LINQ, or type-safe anonymous return values (it seems to me the compiler should certainly be capable of that), it appears to be nearly impossible to cleanly separate the Controller from the View.

    Read the article

  • Parsing xml files locally from assets folder using XmlPullParser

    - by Randolphg
    Im trying to parse a local xml file that I place in my assets folder. I've been trying to do this for almost a week now. Here is my test xml file Test1 Test2 Test3 Test4 Test5 I keep getting the same error: W/System.err(22458): org.xmlpull.v1.XmlPullParserException: unexpected type (position:TEXT Code: public void xmlParser() throws XmlPullParserException, IOException, ParserConfigurationException, SAXException { Log.d("tag", "xmlParsing...."); Arithmetic arthm = new Arithmetic(); XmlPullParserFactory xmlPF = XmlPullParserFactory.newInstance(); xmlPF.setValidating(false); XmlPullParser xml = xmlPF.newPullParser(); InputStream raw = getApplication().getAssets().open("menu.xml"); xml.setInput(raw, null); xml.nextTag(); Log.d("tag", "start parsing...."); String elementText = null; String elemName = null; int nofTags = 0; while (xml.getEventType() != XmlPullParser.END_DOCUMENT) { Log.d("tag", "while(xml.next)..."); switch (xml.getEventType()) { case XmlPullParser.START_DOCUMENT: Log.d("tag", "while (xml.getEventType() != XmlPullParser.END_DOCUMENT)"); break; case XmlPullParser.START_TAG: Log.d("tag", " case XmlPullParser.START_TAG"); elementText = xml.getName(); Log.d("tag", "elementText = " + elementText); if (xml.getEventType() != XmlPullParser.END_TAG) { xml.nextTag(); } break; case XmlPullParser.TEXT: Log.d("tag", "case TEXT"); if (elementText.equals("menu") && xml.isWhitespace()) { Log.d("tag", "<" + elementText + ">"); arthm.menu_name = xml.getText(); Log.d("tag", "value " + xml.getText() + " added"); } else if (elementText.equals("item")) { arthm.description = xml.getText(); Log.d("tag", "value " + xml.getText() + " added"); } else if (elementText.equals("SUBCATEGORY NAME")) { arthm.subcategoryDesc.add(xml.getText()); Log.d("tag", "value " + xml.getText() + " added"); } else if (elementText.equals("SUBCATEGORY DESC")) { arthm.subcategoryName.add(xml.getText()); Log.d("tag", "value " + xml.getText() + " added"); } break; case XmlPullParser.END_TAG: Log.d("tag", "case END_TAG"); nofTags += 1; String tags = Integer.toString(nofTags); Log.d("tags", elementText + " number of tags" + tags); if (xml.nextTag() != XmlPullParser.START_TAG) { xml.next(); } break; case XmlPullParser.END_DOCUMENT: Log.d("tag", "case END_DOCUMENT"); break; default: break; } } Log.d("tag", "Success!"); } Thanks in advance.

    Read the article

  • Is it possible to compile a query in linq-to-objects

    - by Luke101
    I have a linq to objects query in a recursive loop and afraid when the objects approach more then 1000 and a have more then 100 users on the site -- my website will break. so is it possible to compile a linq to objects query. The linq query does nothing more then find the direct children of a node.

    Read the article

  • Is it possible to compile a query for linq-to-objects

    - by Luke101
    I have a linq to objects query in a recursive loop and afraid when the objects approach more then 1000 and a have more then 100 users on the site -- my website will break. so is it possible to compile a linq to objects query. The linq query does nothing more then find the direct children of a node.

    Read the article

  • Add LINQ Auto-Generated Value Marker [Column(IsDbGenerated=true)] in Buddy Class

    - by Alex
    Hello, is it possible to decorate a field of a LINQ generated class with [Column(IsDbGenerated=true)] using a buddy class (which is linked to the LINQ class via [MetadataType(typeof(BuddyMetadata))]) ? My goal is to be able to clear and repopulate the LINQ ORM designer without having to set the "Auto Generate Value" property manually every time to re-establish the fact that certain columns are autogenerated. Thanks!

    Read the article

  • LINQ-to-SQL vs stored procedures?

    - by scottmarlowe
    I took a look at the "Beginner's Guide to LINQ" post here on StackOverflow (http://stackoverflow.com/questions/8050/beginners-guide-to-linq), but had a follow-up question: We're about to ramp up a new project where nearly all of our database op's will be fairly simple data retrievals (there's another segment of the project which already writes the data). Most of our other projects up to this point make use of stored procedures for such things. However, I'd like to leverage LINQ-to-SQL if it makes more sense. So, the question is this: For simple data retrievals, which approach is better, LINQ-to-SQL or stored procs? Any specific pro's or con's? Thanks.

    Read the article

  • LINQ-to-SQL vs stored procedures?

    - by scottmarlowe
    I took a look at the "Beginner's Guide to LINQ" post here on StackOverflow (http://stackoverflow.com/questions/8050/beginners-guide-to-linq), but had a follow-up question: We're about to ramp up a new project where nearly all of our database op's will be fairly simple data retrievals (there's another segment of the project which already writes the data). Most of our other projects up to this point make use of stored procedures for such things. However, I'd like to leverage LINQ-to-SQL if it makes more sense. So, the question is this: For simple data retrievals, which approach is better, LINQ-to-SQL or stored procs? Any specific pro's or con's? Thanks.

    Read the article

  • Performing LINQ Self Join

    - by senfo
    I'm not getting the results I want for a query I'm writing in LINQ using the following: var config = (from ic in repository.Fetch() join oc in repository.Fetch() on ic.Slot equals oc.Slot where ic.Description == "Input" && oc.Description == "Output" select new Config { InputOid = ic.Oid, OutputOid = oc.Oid }).Distinct(); The following SQL returns 53 rows (which is correct), but the above LINQ returns 96 rows: SELECT DISTINCT ic.Oid AS InputOid, oc.Oid AS OutputOid FROM dbo.Config AS ic INNER JOIN dbo.Config AS oc ON ic.Slot = oc.Slot WHERE ic.Description = 'Input' AND oc.Description = 'Output' How would I replicate the above SQL in a LINQ query? Update: I don't think it matters, but I'm working with LINQ to Entities 4.0.

    Read the article

  • Can we replace XML with JSON entirely?

    - by Saeed Neamati
    I'm sure lots of developers are familiar with XML and JSON, and they've used both of them. Thus no point in explaining what they are, and what is their purpose, even in brief. If we try to map their concepts, we can say (correct me if I'm wrong): XML tags are equivalent to JSON {} XML attributes are equivalent to JSON properties XML tag collection is equivalent to JSON [] The only thing I can think of, which doesn't exist in JSON, is XML Namespaces. The question is, considering this mapping, and considering that JSON is highly lighter in this mapping, can we see a world in future (or at least theoretically think of a world) without XML, but with JSON doing everything XML does? Can we use JSON everywhere XML is used? PS: Please note that I've seen this question. It's something entirely different from what I'm asking here. Thus please don't mention duplicate.

    Read the article

  • Loading a new instance of a class through XML not working quite right

    - by Thegluestickman
    I'm having trouble with XML and XNA. I want to be able to load weapon settings through XML to make my weapons easier to make and to have less code in the actual project file. So I started out making a basic XML document, something to just assign variables with. But no matter what I changed it gave me a new error every time. The code below gives me a "XML element 'Tag' not found", I added and it started to say the variables weren't found. What I wanted to do in the XML file as well, was load a texture for the file too. So I created a static class to hold my texture values, then in the Texture tag of my XML document I would set it to that instance too. I think that's were the problems are occuring because that's where the "XML element 'Tag' not found" error is pointing me too. My XML document: <XnaContent> <Asset Type="ConversationEngine.Weapon"> <weaponStrength>0</weaponStrength> <damageModifiers>0</damageModifiers> <speed>0</speed> <magicDefense>0</magicDefense> <description>0</description> <identifier>0</identifier> <weaponTexture>LoadWeaponTextures.ironSword</weaponTexture> </Asset> </XnaContent> My Class to load the weapon XML: public static class LoadWeaponXML { static Weapon Weapons; public static Weapon WeaponLoad(ContentManager content, int id) { Weapons = content.Load<Weapon>(@"Weapons/" + id); return Weapons; } } public static class LoadWeaponTextures { public static Texture2D ironSword; public static void TextureLoad(ContentManager content) { ironSword = content.Load<Texture2D>("Sword"); } } I'm not entirely sure if you can load textures through XML, but any help would be greatly appreciated.

    Read the article

  • Receive the Broadcast program with XML [on hold]

    - by bitmez4
    I have a channel publishing sites and I wanna get into the channel CNN broadcast program.. CNN broadcast the program here: (you can see in source - xml File) http://tvprofil.net/xmltv/data/cnn.info/weekly_cnn.info_tvprofil.net.xml How the data according to the time of withdrawal? For example: Now program: "bitmez's table" next program: "stack's table" in 30 minute Is this possible? UPDATE 1 // -I can take the XML data but to all of XML file- <?php if(!$xml=simplexml_load_file('http://tvprofil.net/xmltv/data/cnn.info/weekly_cnn.info_tvprofil.net.xml')){ trigger_error('XML file -- read error',E_USER_ERROR); } echo 'X-'; foreach($xml as $programme){ echo 'Now: '.$programme->title.' <br/>'; } ?>

    Read the article

  • Unit Testing XML independent of physical XML file

    - by RAbraham
    Hi, My question is: In JUnit, How do I setup xml data for my System Under Test(SUT) without making the SUT read from an XML file physically stored on the file system Background: I am given a XML file which contains rules for creation of an invoice. My job is to convert these rules from XMl to Java Objects e.g. If there is a tag as below in my XML file which indicates that after a period of 30 days, the transaction cannot be invoiced <ExpirationDay>30</ExpirationDay> this converts to a Java class , say ExpirationDateInvoicingRule I have a class InvoiceConfiguration which should take the XML file and create the *InvoicingRule objects. I am thinking of using StAX to parse the XML document within InvoiceConfiguration Problem: I want to unit test InvoiceConfiguration. But I dont want InvoiceConfiguration to read from an xml file physically on the file system . I want my unit test to be independent of any physical stored xml file. I want to create a xml representation in memory. But a StAX parser only takes FileReader( or I can play with the File Object)

    Read the article

  • LINQ to XML contents of child records.

    - by Fossaw
    I have this LINQ to XML enquiry... var Records = from Item in XDoc.Root.Elements("Item") where (string)Item.Element("ItemNumber") == item.ID.ToString select Item; ... where ItemNumber is a reference number used in the XML, (originally written by this program but manually edited by "others"), and item.ID is the database version of the same thing. The query executes, and I can test for the number of entries in the result fine... if (Records.Count() < 1) ... you get the idea. I have established that there is only one record. Each Item has several child fields. I want to test the values of the child fields are reasonable before passing them on to the database update sub-system. The XML is produced by the program, but edited by users, so I need to really check what is coming back. So I tried... if (DB_English.ToString() != Records.Elements("English").ToString()) ... DB_English is from the database, but the XML in Records, does not contain the contents of that field, it contains... System.Xml.Linq.Extensions+<GetElements>d__29`1[System.Xml.Linq.XElement] ... so, how do I get the value of this element in the XML file? I need to check the field in the XML has not been altered, (the manual editors of this data file are not potentially 100% reliable).

    Read the article

  • XML deserialization doubling up on entities

    - by Nathan Loding
    I have an XML file that I am attempting to deserialize into it's respective objects. It works great on most of these objects, except for one item that is being doubled up on. Here's the relevant portion of the XML: <Clients> <Client Name="My Company" SiteID="1" GUID="xxx-xxx-xxx-xxx"> <Reports> <Report Name="First Report" Path="/Custom/FirstReport"> <Generate>true</Generate> </Report> </Reports> </Client> </Clients> "Clients" is a List<Client> object. Each Client object has a List<Report> object within it. The issue is that when this XML is deserialized, the List<Report> object has a count of 2 -- the "First Report" Report object is in there twice. Why? Here's the C#: public class Client { [System.Xml.Serialization.XmlArray("Reports"), System.Xml.Serialization.XmlArrayItem(typeof(Report))] public List<Report> Reports; } public class Report { [System.Xml.Serialization.XmlAttribute("Name")] public string Name; public bool Generate; [System.Xml.Serialization.XmlAttribute("Path")] public string Path; } class Program { static void Main(string[] args) { List<Client> _clients = new List<Client>(); string xmlFile = "myxmlfile.xml"; System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Client>), new System.Xml.Serialization.XmlRootAttribute("Clients")); using (FileStream stream = new FileStream(xmlFile, FileMode.Open)) { _clients = xmlSerializer.Deserialize(stream) as List<Client>; } foreach(Client _client in _clients) { Console.WriteLine("Count: " + _client.Reports.Count); // This write "2" foreach(Report _report in _client.Reports) { Console.WriteLine("Name: " + _report.Name); // Writes "First Report" twice } } } }

    Read the article

  • Filtering data in LINQ with the help of where clause

    - by vik20000in
     LINQ has bought with itself a super power of querying Objects, Database, XML, SharePoint and nearly any other data structure. The power of LINQ lies in the fact that it is managed code that lets you write SQL type code to fetch data.  Whenever working with data we always need a way to filter out the data based on different condition. In this post we will look at some of the different ways in which we can filter data in LINQ with the help of where clause. Simple Filter for an array. Let’s say we have an array of number and we want to filter out data based on some condition. Below is an example int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums =                 from num in numbers                 where num < 5                 select num;   Filter based on one of the property in the class. With the help of LINQ we can also filer out data from a list based on value of some property. var soldOutProducts =                 from prod in products                 where prod.UnitsInStock == 0                 select prod; Filter based on Multiple of the property in the class. var expensiveInStockProducts =         from prod in products         where prod.UnitsInStock > 0 && prod.UnitPrice > 3.00M         select prod; Filter based on the index of the Item in the list.In the below example we can see that we are able to filter data based on the index of the item in the list. string[] digits = { "zero", "one", "two", "three", "four", "five", "six"}; var shortDigits = digits.Where((digit, index) => digit.Length < index); There are many other way in which we can filter out data in LINQ. In the above post I have tried and shown few ways using the LINQ. Vikram

    Read the article

  • Read XML Files using LINQ to XML and Extension Methods

    - by psheriff
    In previous blog posts I have discussed how to use XML files to store data in your applications. I showed you how to read those XML files from your project and get XML from a WCF service. One of the problems with reading XML files is when elements or attributes are missing. If you try to read that missing data, then a null value is returned. This can cause a problem if you are trying to load that data into an object and a null is read. This blog post will show you how to create extension methods to detect null values and return valid values to load into your object. The XML Data An XML data file called Product.xml is located in the \Xml folder of the Silverlight sample project for this blog post. This XML file contains several rows of product data that will be used in each of the samples for this post. Each row has 4 attributes; namely ProductId, ProductName, IntroductionDate and Price. <Products>  <Product ProductId="1"           ProductName="Haystack Code Generator for .NET"           IntroductionDate="07/01/2010"  Price="799" />  <Product ProductId="2"           ProductName="ASP.Net Jumpstart Samples"           IntroductionDate="05/24/2005"  Price="0" />  ...  ...</Products> The Product Class Just as you create an Entity class to map each column in a table to a property in a class, you should do the same for an XML file too. In this case you will create a Product class with properties for each of the attributes in each element of product data. The following code listing shows the Product class. public class Product : CommonBase{  public const string XmlFile = @"Xml/Product.xml";   private string _ProductName;  private int _ProductId;  private DateTime _IntroductionDate;  private decimal _Price;   public string ProductName  {    get { return _ProductName; }    set {      if (_ProductName != value) {        _ProductName = value;        RaisePropertyChanged("ProductName");      }    }  }   public int ProductId  {    get { return _ProductId; }    set {      if (_ProductId != value) {        _ProductId = value;        RaisePropertyChanged("ProductId");      }    }  }   public DateTime IntroductionDate  {    get { return _IntroductionDate; }    set {      if (_IntroductionDate != value) {        _IntroductionDate = value;        RaisePropertyChanged("IntroductionDate");      }    }  }   public decimal Price  {    get { return _Price; }    set {      if (_Price != value) {        _Price = value;        RaisePropertyChanged("Price");      }    }  }} NOTE: The CommonBase class that the Product class inherits from simply implements the INotifyPropertyChanged event in order to inform your XAML UI of any property changes. You can see this class in the sample you download for this blog post. Reading Data When using LINQ to XML you call the Load method of the XElement class to load the XML file. Once the XML file has been loaded, you write a LINQ query to iterate over the “Product” Descendants in the XML file. The “select” portion of the LINQ query creates a new Product object for each row in the XML file. You retrieve each attribute by passing each attribute name to the Attribute() method and retrieving the data from the “Value” property. The Value property will return a null if there is no data, or will return the string value of the attribute. The Convert class is used to convert the value retrieved into the appropriate data type required by the Product class. private void LoadProducts(){  XElement xElem = null;   try  {    xElem = XElement.Load(Product.XmlFile);     // The following will NOT work if you have missing attributes    var products =         from elem in xElem.Descendants("Product")        orderby elem.Attribute("ProductName").Value        select new Product        {          ProductId = Convert.ToInt32(            elem.Attribute("ProductId").Value),          ProductName = Convert.ToString(            elem.Attribute("ProductName").Value),          IntroductionDate = Convert.ToDateTime(            elem.Attribute("IntroductionDate").Value),          Price = Convert.ToDecimal(elem.Attribute("Price").Value)        };     lstData.DataContext = products;  }  catch (Exception ex)  {    MessageBox.Show(ex.Message);  }} This is where the problem comes in. If you have any missing attributes in any of the rows in the XML file, or if the data in the ProductId or IntroductionDate is not of the appropriate type, then this code will fail! The reason? There is no built-in check to ensure that the correct type of data is contained in the XML file. This is where extension methods can come in real handy. Using Extension Methods Instead of using the Convert class to perform type conversions as you just saw, create a set of extension methods attached to the XAttribute class. These extension methods will perform null-checking and ensure that a valid value is passed back instead of an exception being thrown if there is invalid data in your XML file. private void LoadProducts(){  var xElem = XElement.Load(Product.XmlFile);   var products =       from elem in xElem.Descendants("Product")      orderby elem.Attribute("ProductName").Value      select new Product      {        ProductId = elem.Attribute("ProductId").GetAsInteger(),        ProductName = elem.Attribute("ProductName").GetAsString(),        IntroductionDate =            elem.Attribute("IntroductionDate").GetAsDateTime(),        Price = elem.Attribute("Price").GetAsDecimal()      };   lstData.DataContext = products;} Writing Extension Methods To create an extension method you will create a class with any name you like. In the code listing below is a class named XmlExtensionMethods. This listing just shows a couple of the available methods such as GetAsString and GetAsInteger. These methods are just like any other method you would write except when you pass in the parameter you prefix the type with the keyword “this”. This lets the compiler know that it should add this method to the class specified in the parameter. public static class XmlExtensionMethods{  public static string GetAsString(this XAttribute attr)  {    string ret = string.Empty;     if (attr != null && !string.IsNullOrEmpty(attr.Value))    {      ret = attr.Value;    }     return ret;  }   public static int GetAsInteger(this XAttribute attr)  {    int ret = 0;    int value = 0;     if (attr != null && !string.IsNullOrEmpty(attr.Value))    {      if(int.TryParse(attr.Value, out value))        ret = value;    }     return ret;  }   ...  ...} Each of the methods in the XmlExtensionMethods class should inspect the XAttribute to ensure it is not null and that the value in the attribute is not null. If the value is null, then a default value will be returned such as an empty string or a 0 for a numeric value. Summary Extension methods are a great way to simplify your code and provide protection to ensure problems do not occur when reading data. You will probably want to create more extension methods to handle XElement objects as well for when you use element-based XML. Feel free to extend these extension methods to accept a parameter which would be the default value if a null value is detected, or any other parameters you wish. NOTE: You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose “Tips & Tricks”, then "Read XML Files using LINQ to XML and Extension Methods" from the drop-down. Good Luck with your Coding,Paul D. Sheriff  

    Read the article

  • JBoss AS: use .xml files in the properties-service.xml

    - by fgysin
    The properties service (configured in properties-service.xml) in JBoss application server lets you specify external .properties files that are loaded and can then be accessed as system properties from the deployed applications. (See here http://community.jboss.org/wiki/PropertiesService for more info...) Is it also possible to load config files in the .xml format instead of .properties? I know it is possible for certain given configs like for example the mail-service.xml and the jboss-log4j.xml... But they are both loaded directly by JBoss, and not via the properties service.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >