473,695 Members | 2,969 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 3872
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
5311
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...
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
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
9122
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
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
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...
0
5841
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4587
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3018
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2281
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.