473,695 Members | 3,031 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Update an Existing Element Using Linq

I am trying to write an application among which one of the functions is to
determine the number of unique extensions found in a directory and all of
its sub directories. I am trying to use Linq to XML to do this.

Below is the code being used to accomplish what I am trying to do. In the
"if" statement, I am trying to update the <Count></CountElement to
"TESTING". However what I will really want is to add 1 to the existing
numerical value.

Your help is greatly appreciated!
System.IO.FileI nfo myCurrentFile;
System.Xml.Linq .XElement myFileCountCurr entElement;

var Extensions = new XElement("Count ", (from Extension in
_myFileExtensio nCount.LinqXDoc ument.Descendan ts("Extension" ) where
Extension.Eleme nt("Name").Valu e == myCurrentFile.E xtension.ToLowe r()
select new
{
Name =
Extension.Eleme nt("Name").Valu e,
Count =
Extension.Eleme nt("Count").Val ue,
}));
// An unaccounted file extension has been found. Let's add it.
if (Extensions.IsE mpty == true)
{
myFileCountCurr entElement = _myFileExtensio nCount.LinqXDoc ument.Root;
myFileCountCurr entElement =
_myFileExtensio nCount.AppendXm lElement(myFile CountCurrentEle ment,
"Extension" , null);
_myFileExtensio nCount.AppendXm lElement(myFile CountCurrentEle ment,
"Name", myCurrentFile.E xtension.ToLowe r());
_myFileExtensio nCount.AppendXm lElement(myFile CountCurrentEle ment,
"Count", "1");
}
else
{
Extensions.SetV alue("TESTING") ;
}

Below is the XML output that I am getting.
<?xml version="1.0" encoding="utf-8" ?>
- <FileExtensions >
- <Extension>
<Name>.m4b</Name>
<Count>1</Count>
</Extension>
- <Extension>
<Name>.docx</Name>
<Count>1</Count>
</Extension>
- <Extension>
<Name>.doc</Name>
<Count>1</Count>
</Extension>
- <Extension>
<Name>.xls</Name>
<Count>1</Count>
</Extension>
- <Extension>
<Name>.xlsx</Name>
<Count>1</Count>
</Extension>
</FileExtensions>

Oct 30 '08 #1
5 5311
Edwin wrote:
Below is the XML output that I am getting.
<?xml version="1.0" encoding="utf-8" ?>
- <FileExtensions >
- <Extension>
<Name>.m4b</Name>
<Count>1</Count>
</Extension>
- <Extension>
<Name>.docx</Name>
<Count>1</Count>
</Extension>
- <Extension>
<Name>.doc</Name>
<Count>1</Count>
</Extension>
- <Extension>
<Name>.xls</Name>
<Count>1</Count>
</Extension>
- <Extension>
<Name>.xlsx</Name>
<Count>1</Count>
</Extension>
</FileExtensions>
Here is an example that adds 1 to each Count element in the sample above:

XDocument doc = XDocument.Parse (@"<FileExtensi ons>
<Extension>
<Name>.m4b</Name>
<Count>1</Count>
</Extension>
<Extension>
<Name>.docx</Name>
<Count>1</Count>
</Extension>
<Extension>
<Name>.doc</Name>
<Count>1</Count>
</Extension>
<Extension>
<Name>.xls</Name>
<Count>1</Count>
</Extension>
<Extension>
<Name>.xlsx</Name>
<Count>1</Count>
</Extension>
</FileExtensions> ");
foreach (XElement ext in doc.Root.Elemen ts("Extension") ) {
ext.SetElementV alue("Count", (int)ext.Elemen t("Count")
+ 1);
}
doc.Save(Consol e.Out);

HTH

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Oct 30 '08 #2
I do not want to update every <Count></Countfor every extension. I just
want to udpate the <Count></Countonly if the <Name></Nameapplies for the
current extension being looked at.

For example:

<Extension>
<Name>.m4b</Name>
<Count>10</Count>
</Extension>
<Extension>
<Name>.docx</Name>
<Count>7</Count>
</Extension>
<Extension>
<Name>.doc</Name>
<Count>324</Count>
</Extension>
<Extension>
<Name>.xls</Name>
<Count>98</Count>
</Extension>
<Extension>
<Name>.xlsx</Name>
<Count>45</Count>
</Extension>
</FileExtensions>

Oct 30 '08 #3
Edwin wrote:
I do not want to update every <Count></Countfor every extension. I
just want to udpate the <Count></Countonly if the <Name></Name>
applies for the current extension being looked at.
Well my code was just meant as an example.
Here is a different example that updates Count for one Extension element:

XDocument doc = XDocument.Parse (@"<FileExtensi ons>
<Extension>
<Name>.m4b</Name>
<Count>10</Count>
</Extension>
<Extension>
<Name>.docx</Name>
<Count>7</Count>
</Extension>
<Extension>
<Name>.doc</Name>
<Count>324</Count>
</Extension>
<Extension>
<Name>.xls</Name>
<Count>98</Count>
</Extension>
<Extension>
<Name>.xlsx</Name>
<Count>45</Count>
</Extension>
</FileExtensions> ");

string exampleExt = ".docx";
XElement extension = doc.Root.Elemen ts("Extension") .Where(e
=e.Element("Nam e").Value == exampleExt).Fir stOrDefault();
if (extension != null)
{
extension.SetEl ementValue("Cou nt", 1 +
(int)extension. Element("Count" ));
}
doc.Save(Consol e.Out);
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Oct 30 '08 #4
Excellent! It worked!

I am not sure I understand it but it did exactly what I wanted it to do. I
now have to learn what exactly is happening.

Thanks for your help!

Oct 30 '08 #5
Edwin wrote:
I am not sure I understand it but it did exactly what I wanted it to
do. I now have to learn what exactly is happening.
It is not that complicated, just uses LINQ to XML properties (like Root)
and methods (like Elements("Exten sion")) and LINQ queries with a lambda
expression:

string exampleExt = ".docx";
XElement extension = doc.Root.Elemen ts("Extension") .Where(e
=e.Element("Nam e").Value == exampleExt).Fir stOrDefault();
if (extension != null)
{
extension.SetEl ementValue("Cou nt", 1 +
(int)extension. Element("Count" ));
}

So doc.Root accesses the root element, doc.Root.Elemen ts("Extension" )
all "Extension" child elements of the Root. Then the LINQ Where method
filters those elements with the lambda expression
e =e.Element("Nam e").Value == exampleExt
meaning it takes those "Extension" elements which have a "Name" child
element where the Value is equal to exampleExt.

FirstOrDefault( ) simply means we want only the first of those filtered
elements or null if there is noone.

Once we have found an element all we need to do is set the value of the
"Count" child element using SetElementValue by incrementing the value by
one, to do that we can cast the "Count" child element to an int and add
1. That cast works as XElement provides
http://msdn.microsoft.com/en-us/libr..._explicit.aspx
to cast do a lot of CLR types.

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Oct 30 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
5782
by: yinjennytam | last post by:
Hi all, I'm new to .NET and XML and I have a question. Given an XML file, I want to navigate its content and look for one or two particular elements to get their values. At this point, it suffices to open the XML file for read-only access. Once I have processed these values, I might need to update a bunch of subelements of a certain element. For example, I may need to update the Field Name attribute plus the DataField element value...
3
10226
by: thomas | last post by:
I want to use a priority_queue like STL data structure. But I found that priority_queue cannot update element value: only pop/ push is supported. I'm using priority_queue to implement the prim MST algorithm. So I need the priority_queue to contain the key values for each vertex not included in the final tree. Of course the pop and push operation is what I need, but I also need to update the weight value. Can I use priority_queue to...
5
1310
by: Nilla | last post by:
hi, I'm trying to write the simplest db application using C#, ASP and LINQtosQL but cannot get the Update function to work. I have used the codemodel from a sample called IntroToLinq. My Insert and Get functions work, but the Update does nothing. No errors are thrown and no changes are made. Here's my code In the DBHelper class:
4
3486
by: karthik25 | last post by:
Hi All, I have a problem in finding control in a dynamically created updated panel. I have given the code below. Following is just a starting effort in a completely dynamic user control. I am experimenting before getting to the actual part. This is what I am trying to do: * Create a tab container dynamically * Create 5 tabs dynamically * Add an update panel to each of the tabs
0
2357
by: mesut | last post by:
Hi, I'm using LINQ.. and I would like to understand if it's a bug or not in LINQ... I've a situation like: I'm reading all records via "Select" Statement and a specific select statment #1 record retrieves the record and propose for Delete or Update... when I make changes and click on Update I get "DuplicateKeyException Cannot add an entity with a key that is already in use. "
5
3872
by: Edwin | last post by:
I am trying to write an application among which one of the functions is to determine the number of unique extensions found in a directory and all of its sub directories. I am trying to use Linq to XML to do this. Below is the code being used to accomplish what I am trying to do. In the "if" statement, I am trying to update the <Count></CountElement to "TESTING". However what I will really want is to add 1 to the existing numerical...
1
1477
by: Sergey Topychkanov | last post by:
I have SQL SERVER 2008 Express and C# Express 2008 - both sp1. I can remove and update data in my database only thru direct SQL query thru database explorer, but quite unable to do it through dataset and linq. Thanks in advance Sergey
7
2439
by: shanthidiana | last post by:
hi All, I am new to dot net... i am learning it and I am doing my masters project in c# dot net with sql server 2000 backend... The issue i am having now is... i am having a gridview, upon selection of one of the rows, the row data is loaded into the textbox and dropdowns, so that when changes are made and update button is hit, the data is updated in the backend... all works fine except for the update :( issue is with postback but i...
1
6350
by: nadavgg | last post by:
Hi, I have recently developed a C# application using Linq. I am getting from an external database a list of profiles I need to process, some are new and some are already in the database, and need to be updated. What I do today is go over the profile list and check each profile if such exists I update otherwise I insert - this solution is working fine. I am sure there is a way to use bulk insert/update something like UPDATE ON DUPLICATE, this...
0
8640
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8582
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9001
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8860
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7672
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6498
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4348
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
1984
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.