473,804 Members | 3,251 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 3884
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
5785
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
10240
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
1315
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
3493
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
2366
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
5318
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
2448
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
6396
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
9708
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
10588
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
10085
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
9161
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
7623
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
5527
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...
0
5662
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4302
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
3
2998
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.