Home > Blogs > Eric Shupps | The SharePoint Cowboy > Posts > Jousting with XML - Adding Attributes to Existing Nodes
 
Eric Shupps eshupps The SharePoint Cowboy is the founder and President of BinaryWave, a leading provider of operational intelligence solutions for Microsoft SharePoint. Eric Shupps eshupps The SharePoint Cowboy has worked with SharePoint Products and Technologies since 2001 as a consultant, administrator, architect, developer and trainer. he is an advisory committee member of the Dallas/Ft. Worth SharePoint Community group and participating member of user groups throughout the United Kingdom. Eric Shupps eshupps The SharePoint Cowboy has authored numerous articles on SharePoint, speaks at user group meetings and conferences around the world, and publishes a popular SharePoint blog at http://www.sharepointcowboy.com. Presentations by Eric Shupps eshupps The SharePoint Cowboy Webinar - Migrating Legacy On Premise Solutions to SharePoint Online and Windows Azure featuring Eric Shupps Who are you and what do you want - Working with OAuth in SharePoint 2013 SharePoint is Talking Are You Listening? Eric Shupps SharePoint 2013 Performance Enhancements Taking Advantage of the SharePoint 2013 REST API Eric Shupps on Improving Performance with New Features in SharePoint 2013 SharePoint 2013 New and Improved Migrating Legacy On Premise Solutions to SharePoint Online and Windows Azure Eric Shupps Presents SharePoint 2013 Real World Help Desk App End to End Windows Azure Apps for SharePoint 2013 Eric Shupps Demonstrates Customizing the Visual Studio 2010 SharePoint Deployment Process Introduction to SharePoint Development SharePoint 2010 Unit and Integration Testing with Eric Shupps Building Enterprise Records Management Solutions for SharePoint 2010 Taming Information Chaos in SharePoint 2010 SharePoint 2010 Performance and Capacity Planning Best Practices Building Dynamic Applications with the SharePoint Client Object Model Articles by Eric Shupps eshupps The SharePoint Cowboy Eric Shupps' Ten Steps to Optimize SharePoint Performance Webcasts by Eric Shupps eshupps The SharePoint Cowboy Secrets of SharePoint Part 5: Configuring Microsoft Office SharePoint Server 2007 for Optimal Performance Creating End User SharePoint Solutions for Performance and Scalability SharePoint 2010 Performance Enhancements for Administrators by Eric Shupps Microsoft SharePoint Server 2010 for the ASP.NET Developer Eric Shupps on Following Best Practices and Avoiding Common Errors with Microsoft Office SharePoint Server 2007 Development Eric Shupps - SharePoint Performance and Capacity Planning Essentials Troubleshooting Common Performance Problems in SharePoint 2010 Videos by Eric Shupps eshupps The SharePoint Cowboy Channel 9 Interview with Eric Shupps SharePoint TechTalk with Eric Shupps - Different Views on Social Computing SharePoint Post-Deployment Planning and Management with Eric Shupps SmartTrack for SharePoint Feature Overview SmartTrack for SharePoint Podcasts by Eric Shupps eshupps The SharePoint Cowboy SharePoint Pod Show - Design for Performance (Eric Shupps) SharePoint Pod Show - Test Driven Development with Andrew Woodward and Eric Shupps eshupps The SharePoint Cowboy Run As Radio - Eric Shupps Improves SharePoint Performance
SmartTrack for SharePoint Eric Shupps Eric Alan Shupps eshupps @eshupps SharePoint Cowboy BinaryWave

 
​The SharePoint Cowboy


photo of  Eric Shupps
BinaryWave
611 S. Main St., Suite 400
Grapevine , TX , 76051 USA
Eric Shupps and Eric Alan Shupps with BinaryWave the BinaryWave Inc in BinaryWave Incorporated around SmartTrack beside SharePoint Monitoring through SharePoint alongside SharePoint Monitoring visiting @eshupps via eshupps near SharePoint performance and SharePoint management. The SharePoint cowboy eshupps BinaryWave and more on Operational Intelligence via Eric Alan Shupps SharePoint blog. SharePoint monitoring is a hot topic along with SharePoint Performance Measurement and SharePoint tips and tricks from Eric Shupps for SmartTrack. Another Eric Shupps on Technology and Eric Shupps on SharePoint with a new SharePoint Post from Eric Shupps. New BinaryWave post through BinaryWave Inc. and with another SharePoint blog we get to Eric Alan Shupps Blog about SharePoint development. That's Eric Shupps - BinaryWave or Eric Alan Shupps Fort Worth Grapevine Texas Dallas of BinaryWave talking about BinaryWave Operational Intelligence at the SharePoint Cowboy blog and on twitter as @eshupps. Of course SharePoint Administration is on topic for eshupps and another great post from Eric Shupps regarding BinaryWave SharePoint and SharePoint Maintenance.
March 16
Jousting with XML - Adding Attributes to Existing Nodes

This isn't technically a SharePoint-related post as the issue is one of pure XML manipulation but I ran across it while building a custom solution in SharePoint and it took hours to figure it out so I thought it merited some attention. When working with XML, as is often the case in SharePoint (especially when using web services), there is often a need to modify some fragment of XML to support a resultant operation. In this particular instance, I had an XML fragment similar to the following:

<Books>
<Book name="My Book" id="book1">
<Chapters>
<Chapter name="Chapter 1" />
<Chapter name="Chapter 2" />
<Chapter name="Chapter 3" />
</Chapters>
</Book>
</Books>

In order to populate a TreeView and from there construct a link for each node with the proper parameters, I needed to add the ID of the parent Book object to each one of the Chapter nodes as a new attribute. Sounds simple enough. I started with something like this (error trapping and null checks omitted for brevity):

 

XmlDocument doc = new XmlDocument();
doc.LoadXml(booksxml);
XmlNode bookNode = doc.DocumentElement.SelectSingleNode("Book");
string bookId = bookNode.Attributes["id"].Value;

XmlAttribute parentBookId = doc.CreateAttribute("bookid");
parentBookId.Value = bookId;

XmlNodeList chapterNodes = bookNode.SelectNodes("Chapters/Chapter");

foreach (XmlNode chapterNode in chapterNodes)
{
   chapterNode.Attributes.Append(parentBookId);
}


Easy, right? Not so fast. Under no circumstances would the new "bookid" attribute get added to each Chapter node in the resultant XML string. I tried all kinds of things, including converting the node to an XmlElement and using the SetAttribute() method, moving the value assignment into the node itself, and so on, but nothing seemed to work. For whatever reason it just ignored my new attribute and moved right along. What was really frustrating was that in debug mode I could see the new attribute being added to each node as I stepped through it. But when the code ran the final output was unchanged.

After much searching around and cursing XML in general, I tried what seemed a silly bit of code:

 

XmlDocument doc = new XmlDocument();
doc.LoadXml(booksxml);
XmlNode bookNode = doc.DocumentElement.SelectSingleNode("Book");
string bookId = bookNode.Attributes["id"].Value;

XmlNodeList chapterNodes = bookNode.SelectNodes("Chapters/Chapter");

foreach (XmlNode chapterNode in chapterNodes)
{
   XmlAttribute parentBookId = chapterNode.OwnerDocument.CreateAttribute("bookid");
   parentBookId.Value = bookId;
   chapterNode.Attributes.Append(parentBookId);
}


Voila! It worked. Moving the creation of the new attribute element into the context of the current node did the trick. That's a bit cumbersome, to say the least, especially as my actual code contained several nested collections of child nodes, so I had to repeat the process for each node in the subsequent collections, each time changing the variable name of the new attribute but leaving the actual attribute name ("bookid") the same. I've since tested it in several variations (.NET Framework 3.5) and found that this is the only method that seems to work. My final XML looked just like I wanted it to:

<Books>
<Book name="My Book" id="book1">
<Chapters>
<Chapter name="Chapter 1" bookid="book1" />
<Chapter name="Chapter 2" bookid="book1" />
<Chapter name="Chapter 3" bookid="book1" />
</Chapters>
</Book>
</Books>

I'd love to know what's going on here. Why is a globally declared (in the context of the XML document itself) attribute not viable while a locally declared (for each node) attribute that's created in the context of the parent document perfectly feasible? It sure makes for some ugly code and the test routines aren't very clean. If anyone has some insight to share please enlighten me. On the other hand, for once it wasn't some weird SharePoint-only thing, so I guess I should be thankful for that…

 

 

 

 

 

Comments

Good old XML

I hear ya Eric!  I've had many a battle myself with XML, often times cursing at the inventors of XML as I struggle to make the mundane happen. :-)
Thanks for posting your insight on Attributes!
System Account on 3/19/2010 11:38 AM

You must Clone the node

It has nothing to do with the scope. The problem is that you are trying to add the same attribute node to multiple elements.
What you need to to is call clone on the attribute.

            foreach (XmlNode chapterNode in chapterNodes)
            {
                chapterNode.Attributes.Append( parentBookId.Clone() as XmlAttribute );
            }
System Account on 3/19/2010 3:44 PM

You must Clone the node

It has nothing to do with the scope. The problem is that you are trying to add the same attribute node to multiple elements.
What you need to to is call clone on the attribute.

            foreach (XmlNode chapterNode in chapterNodes)
            {
                chapterNode.Attributes.Append( parentBookId.Clone() as XmlAttribute );
            }
System Account on 3/19/2010 3:44 PM

Add Comment

Items on this list require content approval. Your submission will not appear in public views until approved by someone with proper rights. More information on content approval.

Title


Body *


Comment Date *

Select a date from the calendar.
Enter the current date to prevent automated spambot comments.

Spam Prevention *


How many letters, not including spaces, does it take to spell "SharePoint Cowboy"?

Attachments

 
photo of Eric Shupps Eric Alan Shupps eshupps @eshupps SharePoint Cowboy BinaryWave Eric Shupps
BinaryWave
611 S. Main St., Suite 400
Grapevine , TX , 76051 USA

 
 
 
Eric Shupps Eric Alan Shupps eshupps @eshupps SharePoint Cowboy BinaryWave 

Eric Shupps LinkedIn Eric Shupps Twitter Eric Shupps Facebook Eric Shupps Google+
 
 

 


 


BinaryWave Eric Shupps eshupps The SharePoint Cowboy SharePoint monitoring SharePoint monitoring tool SharePoint metrics SharePoint administratrion SharePoint monitoring best practices SharePoint management SharePoint management tool SharePoint operations SharePoint operationsmanagement SharePoint administration SharePoint administration tool SharePoint SLA SharePoint service level agreement SharePoint operational intelligence SharePoint performance SharePoint performance monitoring SharePoint analytics SharePoint real-time SharePoint intelligence SharePoint ITIL SharePoint service operations SharePoint uptime SharePoint alerts SharePoint health SharePoint tools SharePoint metrics SharePoint diagnostics SharePoint SmartTrack SmartTrack Operational Intelligence


Copyright © 2013 BinaryWave, Inc. All rights reserved.
This site is brought to you by BinaryWave in cooperation with Eric Shupps Eric Alan Shupps eshupps @eshupps The SharePoint Cowboy. We hope you enjoy the SharePoint-related content on topics such as performance, monitoring, administration, operations, support, business intelligence and more for SharePoint 2010, SharePoint 2013 and Office 365 created by Eric Shupps The SharePoint Cowboy. We also hope you will visit our product pages to learn more about SmartTrack, Operational Analytics for SharePoint, SharePoint monitoring, and SharePoint administration, while also discovering great offers from our partners. Please visit the blog of Eric Alan Shupps, Twitter handle @eshupps, for more information on application development, the SharePoint community, SharePoint performance, and general technology topics. Eric Shupps Eric Alan Shupps eshupps @eshupps The SharePoint Cowboy is the founder and President of BinaryWave, a leading provider of operational support solutions for SharePoint. Eric Shupps Eric Alan Shupps eshupps @eshupps The SharePoint Cowboy has worked with SharePoint Products and Technologies since 2001 as a consultant, administrator, architect, developer and trainer. He is an advisory committee member of the Dallas/Ft. Worth SharePoint Community group and participating member of user groups throughout the United Kingdom. Eric Shupps Eric Alan Shupps eshupps @eshupps The SharePoint Cowboy has authored numerous articles on SharePoint, speaks at user group meetings and conferences around the world, and publishes a popular SharePoint blog at http://www.binarywave.com/blogs/eshupps.