I have an xml file like this:
<post>
<categories>
<category ref="4527" />
<category ref="4528" />
<category ref="4529" />
<category ref="4530" />
<category ref="4531" />
</categories>
</post>
<post>
<categories>
<category ref="4523" />
<category ref="4524" />
<category ref="4525" />
<category ref="4526" />
<category ref="4527" />
</categories>
</post>
Using C# and .Net 4.5 I want to get the first set of category reference numbers, then process them, then move to the next set of category reference numbers and process them. I am hoping that some one can point me in the right direction. I am not sure how to do this using XPath or with Linq to XML or if those are even the right approach. Thanks in advance.
After some responses to some very smart people I was able to use Selman22's train of thought to help me write some XPath. Here is the solution I came up with:
XmlDocument xdoc = new XmlDocument;
xdoc.Load(savePath);
XmlNode root = xdoc.DocumentElement;
// add the namespace
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("bml", "http://www.blogml.com/2006/09/BlogML");
//puts the catagories elements into a list
XmlNodeList blogCatagories = root.SelectNodes("descendant::bml:post/bml:categories", nsmgr);
//loop throught list and place the attribute "ref" into a list and traverse each "ref"
foreach (XmlNode nodeCat in blogCatagories)
{
XmlNodeList catagoryids = nodeCat.SelectNodes("descendant::bml:category/#ref", nsmgr);
foreach (XmlNode nodeID in catagoryids)
{
Console.WriteLine(nodeID.InnerText.ToString());
}
}
First get your categories
var xdDoc = XDocument.Load(path);
var categories = xDoc.Descendants("categories").ToList();
Then loop through your category list
foreach(var cat in categories)
{
var numbers = cat.Elements("category").Select(c => (int)c.Attribute("ref"));
foreach(var number in numbers)
{
// process your numbers
}
}
var xdoc = XDocument.Load(path_to_xml);
var query = from p in xdoc.Root.Descendants("post")
select p.Element("categories")
.Elements("category")
.Select(c => (int)c.Attribute("ref"))
.ToList();
This query will return iterator which will get next sequence of category reference numbers each time you are iterating it.
foreach(List<int> references in query)
{
// process list of references
foreach(int reference in references)
// process reference
}
XPathNavigator xml = new XPathDocument(filename).CreateNavigator();
foreach(XPathNavigator categories in xml.Select("//categories"))
{
foreach(XPathNavigator category in categories.Select("category"))
{
string category_ref = category.GetAttribute("ref", string.Empty);
}
// do processing
}
After some responses to some very smart people I was able to use Selman22's train of thought to help me write some XPath.
XmlDocument xdoc = new XmlDocument;
xdoc.Load(savePath);
XmlNode root = xdoc.DocumentElement;
// add the namespace
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("bml", "http://www.blogml.com/2006/09/BlogML");
//puts the catagories elements into a list
XmlNodeList blogCatagories = root.SelectNodes("descendant::bml:post/bml:categories", nsmgr);
//loop throught list and place the attribute "ref" into a list and traverse each "ref"
foreach (XmlNode nodeCat in blogCatagories)
{
XmlNodeList catagoryids = nodeCat.SelectNodes("descendant::bml:category/#ref", nsmgr);
foreach (XmlNode nodeID in catagoryids)
{
Console.WriteLine(nodeID.InnerText.ToString());
}
}
I would use XPathDocument and XPathNavigator, lots of examples on google like this
http://www.codegod.com/XPathDocument-XPathNavigator-XPathNodeIterator-sample-with-C-AID504.aspx
Related
I'm trying to get the inner text from a node after loading the XML file.
I have tried this code with another file and it worked. But here I can't get the node values.
Can anyone point out what am I doing wrong?
XML file - restaurant_reviews.xml
<?xml version="1.0"?>
<restaurants xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.algonquincollege.com/onlineservice/reviews">
<restaurant>
<name>Laughing Man</name>
<logo>
<name>Visit the Laughing Man</name>
<imagefile>laughing-man.gif</imagefile>
<width unit="px">50</width>
<height unit="px">200</height>
</logo>
</restaurant>
<restaurant>
<name>Gong’s Asian Cuisine</name>
<logo>
<name/>
<imagefile>gong-asian-cuisine.gif</imagefile>
<width unit="px">150</width>
<height unit="px">250</height>
</logo>
</restaurant>
</restaurants>
C# Code
List<string> names = new List<string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(HttpContext.Current.Server.MapPath(#"~/App_Data/restaurant_reviews.xml"));
XmlNodeList nodes = xmlDoc.SelectNodes("/restaurants/restaurant");
foreach (XmlNode itemNode in nodes)
{
XmlNode titleNode = itemNode.SelectSingleNode("name");
if (titleNode != null)
{
names.Add(titleNode.InnerText);
}
}
Whilst this question already has an accepted answer, I wanted to add this anyway, as removing namespaces and manipulating XML in this way doesn't feel right to me, it was added for a reason I suspect.
What I believe is the correct approach is too add an XML Namespace Manager to your XPath query.
var nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsMgr.AddNamespace("r", "http://www.algonquincollege.com/onlineservice/reviews");
Then in your SelectNodes and SelectSingleNodes, you add the namespace to the query and pass in the manager, like so.
XmlNodeList nodes = xmlDoc.SelectNodes("/r:restaurants/r:restaurant", nsMgr);
and
XmlNode titleNode = itemNode.SelectSingleNode("r:name", nsMgr);
But if you're happy with the other solution and can manipulate it in this way then go for it I guess.
If you remove this xmlns="http://www.algonquincollege.com/onlineservice/reviews" in your xml it works. I don't know why but the xmlDoc.SelectNodes("/restaurants/restaurant"); do not find any nodes with this xmlns namespace.
This is the code I worked with and it works:
string xml = #"<?xml version=""1.0""?>
<restaurants xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<restaurant>
<name>Laughing Man</name>
<logo>
<name>Visit the Laughing Man</name>
<imagefile>laughing-man.gif</imagefile>
<width unit=""px"">50</width>
<height unit=""px"">200</height>
</logo>
</restaurant>
<restaurant>
<name>Gong’s Asian Cuisine</name>
<logo>
<name/>
<imagefile>gong-asian-cuisine.gif</imagefile>
<width unit=""px"">150</width>
<height unit=""px"">250</height>
</logo>
</restaurant>
</restaurants>";
List<string> names = new List<string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNodeList nodes = xmlDoc.SelectNodes("/restaurants/restaurant");
foreach (XmlNode itemNode in nodes)
{
XmlNode titleNode = itemNode.SelectSingleNode("name");
if (titleNode != null)
{
names.Add(titleNode.InnerText);
}
}
The problem was with namespace. Thanks to #Sean in the comment section I have resolved the issue. Thanks to #Presi also for pointing out the namespace attribute was the problem.
List<string> names = new List<string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(HttpContext.Current.Server.MapPath(#"~/App_Data/restaurant_reviews.xml"));
var namespaceName = "ns";
var namespacePrefix = string.Empty;
XmlNamespaceManager nameSpaceManager = null;
if (xmlDoc.LastChild.Attributes != null)
{
var xmlns = xmlDoc.LastChild.Attributes["xmlns"];
if (xmlns != null)
{
nameSpaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
nameSpaceManager.AddNamespace(namespaceName, xmlns.Value);
namespacePrefix = namespaceName + ":";
}
}
XmlNodeList nodes = xmlDoc.SelectNodes(string.Format("/{0}restaurants/{0}restaurant", namespacePrefix), nameSpaceManager);
foreach (XmlNode itemNode in nodes)
{
XmlNode titleNode = itemNode.SelectSingleNode(namespacePrefix + "name", nameSpaceManager);
if (titleNode != null)
{
names.Add(titleNode.InnerText);
}
}
This is my feed.
<feed xml:lang="">
<title>NEWS.com.au | Top Stories</title>
<link rel="self" href="http://feeds.news.com.au/public/atom/1.0/news_top_stories_48_48.xml"/>
<link rel="alternate" href="http://news.com.au"/>
<id>http://news.com.au</id>
<rights/>
<entry>
<title>F1’s glaring issues exposed</title>
<link href="www.google.com"/>
<author>
<name>STEVE LARKIN</name>
</author>
<link rel="enclosure" type="image/jpeg" length="2373" href="abc.jpg"/>
</entry>
<entry>
.....
</entry>
</feed>
This is how i am reading the xml.
string downloadfolder = "C:/Temp/Download/abc.xml";
XmlDocument xml = new XmlDocument();
xml.Load(downloadfolder);
XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
string xpath_title = "atom:feed/atom:entry/atom:title";
XmlNodeList nodes_title = xml.SelectNodes(xpath_title, nsmgr);
foreach (XmlNode node_title in nodes_title)
{
Console.WriteLine(node_title.InnerText);
}
string xpath_author = "atom:feed/atom:entry/atom:author";
XmlNodeList nodes_author = xml.SelectNodes(xpath_author, nsmgr);
foreach (XmlNode node_author in nodes_author)
{
Console.WriteLine(node_author.InnerText);
}
string xpath_link = "atom:feed/atom:entry/atom:link";
XmlNodeList nodes_link = xml.SelectNodes(xpath_link, nsmgr);
foreach (XmlNode node_link in nodes_link)
{
Console.WriteLine(node_link.Attributes["href"].Value);
}
I want to read title, link, author inside the <entry> node. i am defining xpath and then iterating the values of each node is there any other way to define xpath once and then iterate all the values from the <entry> node
To operate on all child nodes of <entry> node, you can stop your XPath at /atom:entry. Then inside the loop, select each child nodes as you want, for example :
......
String xpath = "atom:feed/atom:entry";
XmlNodeList nodes2 = xml.SelectNodes(xpath, nsmgr);
foreach (XmlNode node in nodes2)
{
var title = node.SelectSingleNode("./atom:title", nsmgr).InnerText;
var link1 = node.SelectSingleNode("./atom:link[1]", nsmgr).Attributes["href"].Value;
//go on to select and operate on the rest child nodes
//.......
}
Notice that you need to add a dot (.) at the beginning of the XPath to make XPath context relative to current node instead of the entire XML document.
To read the href attribute you will need to modify your xpath expression to...
string xpath = "atom:feed/atom:entry/atom:link";
this will iterate through all links within entries. Then, you will need read that specific attibute's value instead of reading the InnerText
Console.WriteLine(node.Attributes["href"].Value);
Now, if you want to read everything inside the entry elements, xpath will quickly get your code a bit messy. A cleaner solution, IMHO, would be using xml serialization so that you can easily parse/serialize "entries" into POCO objects. Then, you can do whatever you want with these objects
i am trying to grab the TopicName how should i go after it and try different combination but somehow i am unable to get TopicName below is my source codee...
XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing
xdoc.Load(
"http://latestpackagingnews.blogspot.com/feeds/posts/default"
);//loading XML in xml doc
XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("content");//reading node so that we can traverse thorugh the XML
foreach (XmlNode xNode in xNodelst)//traversing XML
{
//litFeed.Text += "read";
}
sample xml file
<content type="application/xml">
<CatalogItems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="sitename.xsd">
<CatalogSource Acronym="ABC" OrganizationName="ABC Corporation" />
<CatalogItem Id="3212" CatalogUrl="urlname">
<ContentItem xmlns:content="sitename.xsd" TargetUrl="url">
<content:SelectionSpec ClassList="" ElementList="" />
<content:Language Value="eng" Scheme="ISO 639-2" />
<content:Source Acronym="ABC" OrganizationName="ABC Corporation" />
<content:Topics Scheme="ABC">
<content:Topic TopicName="Marketing" />
<content:Topic TopiccName="Coverage" />
</content:Topics>
</ContentItem>
</CatalogItem>
</CatalogItems>
</content>
The Topic nodes in your XML are using the content namespace - you need to declare and use the XML namespace in your code, then you can use SelectNodes() to grab the nodes of interest - this worked for me:
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("content", "sitename.xsd");
var topicNodes = xdoc.SelectNodes("//content:Topic", nsmgr);
foreach (XmlNode node in topicNodes)
{
string topic = node.Attributes["TopicName"].Value;
}
Just as a comparison see how easy this would be with Linq to XML:
XDocument xdoc = XDocument.Load("test.xml");
XNamespace ns = "sitename.xsd";
string topic = xdoc.Descendants(ns + "Topic")
.Select(x => (string)x.Attribute("TopicName"))
.FirstOrDefault();
To get all topics you can replace the last statement with:
var topics = xdoc.Descendants(ns + "Topic")
.Select(x => (string)x.Attribute("TopicName"))
.ToList();
If you just need a specific element, then I'd use XPath:
This is a guide to use XPath in C#:
http://www.codeproject.com/KB/XML/usingXPathNavigator.aspx
And this is the query that will get you a collection of your Topics:
//content/CatalogItems/CatalogItem/ContentItem/content:Topics/content:Topic
You could tweak this query depending on what it is you're trying to accomplish, grabbing just a specific TopicName value:
//content/CatalogItems/CatalogItem/ContentItem/content:Topics/content:Topic/#TopicName
XPath is pretty easy to learn. I've done stuff like this pretty quickly with no prior knowledge.
You can paste you XML and xpath query here to test your queries:
http://www.bit-101.com/xpath/
The following quick and dirty LINQ to XML code obtains your TopicNames and prints them on the console.
XDocument lDoc = XDocument.Load(lXmlDocUri);
foreach (var lElement in lDoc.Element("content").Element(XName.Get("CatalogItems", "sitename.xsd")).Elements(XName.Get("CatalogItem", "sitename.xsd")))
{
foreach (var lContentTopic in lElement.Element(XName.Get("ContentItem", "sitename.xsd")).Element(XName.Get("Topics", "sitename.xsd")).Elements(XName.Get("Topic", "sitename.xsd")))
{
string lTitle = lContentTopic.Attribute("TopicName").Value;
Console.WriteLine(lTitle);
}
}
It'd have been a lot shorter if it wasn't for all the namespaces :) (Instead of "XName.Get" you would just use the name of the element).
Is there a way to get the innertext of a node when the node is inside a collection
Currently i have this
Collection<string> DependentNodes = new Collection<string>();
foreach (XmlNode node in nodes)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
DependentNodes.Add(node.ChildNodes[i].InnerXml);
//the reason i'm using InnerXml is that it will return all the child node of testfixture in one single line,then we can find the category & check if there's dependson
}
}
string selectedtestcase = "abc_somewords";
foreach (string s in DependentNodes)
{
if(s.Contains(selectedtestcase))
{
MessageBox.Show("aaa");
}
}
When i debug string s or the index has this inside of it[in a single line]
<testfixture name="1" description="a">
<categories>
<category>abc_somewords</category>
</categories>
<test name="a" description="a">
<dependencies>
<dependson typename="dependsonthis" />
</dependencies>
</test>
</testfixture>
What i'm trying to do is when we reach "testfixture 1" it will find "abc_somewords" & search the "dependson typename"node(if any) and get the "typename"(which is "dependonthis").
Could you use linq to xml. Something like the below might be a decent start
xml.Elements("categories").Where(x => x.Element("category").Value.Contains(selectedtestcase));
This is off the top of my head so might will need refining
P.S. Use XElement.Load or XElement.Parse to get your xml into XElements
Since you already working with XmlNode you could use a XPath expression to select the desired textfixture node, and select the dependency value:
XmlDocument doc = // ...
XmlNode node = doc.SelectSingleNode("//testfixture[contains(categories/category, \"abc\")]/test/dependencies/dependson/");
if (node != null)
{
MessageBox.Show(node.Attributes["typename"]);
}
This selects the dependson node which belongs to a testfixture node with a category containing "abc". node.Attributes["typename"] will return the value of the typename attribute.
Edited:
Updated XPath expression to the more specific question information
Assumptions
As you are looping in your code and wanting to create a collection I'm assuming the actual Xml File has several testfixture nodes inside such as the below assumed example:
<root>
<testfixture name="1" description="a">
<categories>
<category>abc_somewords</category>
</categories>
<test name="a" description="a">
<dependencies>
<dependson typename="dependsonthis" />
</dependencies>
</test>
</testfixture>
<testfixture name="2" description="a">
<categories>
<category>another_value</category>
</categories>
<test name="b" description="a">
<dependencies>
<dependson typename="secondentry" />
</dependencies>
</test>
</testfixture>
<testfixture name="3" description="a">
<categories>
<category>abc_somewords</category>
</categories>
<test name="c" description="a">
<dependencies>
<dependson typename="thirdentry" />
</dependencies>
</test>
</testfixture>
</root>
The Code using Linq to Xml
To use Linq you must reference the following name spaces:
using System.Linq;
using System.Xml.Linq;
Using Linq To Xml on the above assumed xml file structure would look like this:
// To Load Xml Content from File.
XDocument doc1 = XDocument.Load(#"C:\MyXml.xml");
Collection<string> DependentNodes = new Collection<string>();
var results =
doc1.Root.Elements("testfixture")
.Where(x => x.Element("categories").Element("category").Value.Contains("abc_somewords"))
.Elements("test").Elements("dependencies").Elements("dependson").Attributes("typename").ToArray();
foreach (XAttribute attribute in results)
{
DependentNodes.Add(attribute.Value.Trim());
}
Result
The resulting Collection will contain the following:
As you can see, only the text of the typename attribute has been extracted where the dependson nodes where in a testfixture node which contained a category node with the value of abc_somewords.
Additional Notes
If you read the xml from a string you can also use this:
// To Load Xml Content from a string.
XDocument doc = XDocument.Parse(myXml);
If your complete Xml structure is different, feel free to post it and I change the code to match.
Have Fun.
I don't know what is "nodes" you are using.
Here is code with your requirement(What I understood).
Collection<XmlNode> DependentNodes = new Collection<XmlNode>();
XmlDocument xDoc = new XmlDocument();
xDoc.Load(#"Path_Of_Your_xml");
foreach (XmlNode node in xDoc.SelectNodes("testfixture")) // Here I am accessing only root node. Give Xpath if ur requrement is changed
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
DependentNodes.Add(node.ChildNodes[i]);
}
}
string selectedtestcase = "abc_somewords";
foreach (var s in DependentNodes)
{
if (s.InnerText.Contains(selectedtestcase))
{
Console.Write("aaa");
}
}
using System;
using System.Xml;
namespace ConsoleApplication6
{
class Program
{
private const string XML = "<testfixture name=\"1\" description=\"a\">" +
"<categories>" +
"<category>abc_somewords</category>" +
"</categories>" +
"<test name=\"a\" description=\"a\">" +
"<dependencies>" +
"<dependson typename=\"dependsonthis\" />" +
"</dependencies>" +
"</test>" +
"</testfixture>";
static void Main(string[] args)
{
var document = new XmlDocument();
document.LoadXml(XML);
var testfixture = document.SelectSingleNode("//testfixture[#name = 1]");
var category = testfixture.SelectSingleNode(".//category[contains(text(), 'abc_somewords')]");
if(category != null)
{
var depends = testfixture.SelectSingleNode("//dependson");
Console.Out.WriteLine(depends.Attributes["typename"].Value);
}
Console.ReadKey();
}
}
}
Output: dependsonthis
I'm currently working with an XML request, and am trying to create a Reply Document that has multiple child nodes of the same name in the call, so what I'm trying to return is:
<Reply Document>
<ConfirmationItem name = "One">
<ItemDetail />
</ConfirmationItem>
<ConfirmationItem name = "Two">
<ItemDetail />
</ConfirmationItem>
...
<ConfirmationItem name = "Twenty">
<ItemDetail />
</ConfirmationItem>
</Reply Document>
I did a bit of research and found this thread: XmlReader AppendChild is not appending same child value in which the accepted answer was that the OP had to create new Elements to be able to append to the end instead of overwrite the first.
My original code is below, it creates the XmlNode from the incoming Request and appends the result to the XmlDocument itself:
//p_transdoc is the XmlDocument that holds all the items to process.
XmlNodeList nodelst_cnfrm = p_transdoc.SelectNodes("//OrderRequest");
foreach (XmlNode node in nodelst_cnfrm)
{
//this is just an XML Object
XmlNode node_cnfrm_itm = this.CreateElement("ConfirmationItem");
node_cnfrm_itm.Attributes.Append(this.CreateAttribute("name")).InnerText = p_transdoc.Attributes["name"].InnerText;
XmlNode node_itmdtl = this.CreateElement("ItemDetail");
node_cnfrm_itm.AppendChild(node_itmdtl);
//xml_doc is the return XML request
xml_doc.AppendChild(node_cnfrm_itm);
}
So after reading that thread and the answer, I tried to change the code to use a new XmlElement each pass through.
//p_transdoc is the XmlDocument that holds all the items to process.
XmlNodeList nodelst_cnfrm = p_transdoc.SelectNodes("//OrderRequest");
foreach (XmlNode node in nodelst_cnfrm)
{
XmlElement node_cnfrm_itm = new XmlElement();
node_cnfrm_itm = this.CreateElement("ConfirmationItem");
node_cnfrm_itm.Attributes.Append(this.CreateAttribute("name")).InnerText = p_transdoc.Attributes["name"].InnerText;
XmlElement node_itmdtl = new XmlElement();
node_itmdtl = this.CreateElement("ItemDetail");
node_cnfrm_itm.AppendChild(node_itmdtl);
//xml_doc is the return XML request
xml_doc.AppendChild(node_cnfrm_itm);
}
But not only does that not work, it returns a server error. So I've come to you for help. Right now this code is just returning one ConfirmationItem. How would I be able to append the ConfirmationItem to the end of the Document instead of overwrite it, to be able to return as many as were sent in?
(I should point out that this code has been heavily formatted for ease of readability, simplicity, and to reduce clutter. Any typographical errors are purely because of the Asker's internal failure at effective proofreading).
Assuming xml_doc is the xml with the ConfirmationItems you need to create the XmlElements with the new XmlDocument. XmlDocument.CreateElement. Hence I use the Linq extension method OfType<>() here to only return the XmlNode objects of the type XmlElement.
// dummy data
XmlDocument p_transdoc = new XmlDocument();
p_transdoc.LoadXml(#"
<root name='rootAttribute'>
<OrderRequest name='one' />
<OrderRequest name='two' />
<OrderRequest name='three' />
</root>
");
XmlDocument xml_doc = new XmlDocument();
xml_doc.LoadXml("<ReplyDocument />");
foreach (var node in p_transdoc.SelectNodes("//OrderRequest").OfType<XmlElement>())
{
XmlElement node_cnfrm_itm = xml_doc.CreateElement("ConfirmationItem");
node_cnfrm_itm = xml_doc.DocumentElement.AppendChild(node_cnfrm_itm) as XmlElement;
node_cnfrm_itm.SetAttribute("name", node.GetAttribute("name"));
XmlElement node_itmdtl = xml_doc.CreateElement("ItemDetail");
node_itmdtl = node_cnfrm_itm.AppendChild(node_itmdtl) as XmlElement;
}
The method CreateElement returns an XmlElement so you can use the methods SetAttribute and GetAttribute.
The code: p_transdoc.Attributes["name"].InnerText doesn't seem right. If you want to get the attributes for the root element of the document you need to type: p_transdoc.DocumentElement.GetAttribute("name")
IMO this is MUCH easier if you're using Linq to XML.
In Linq to XML this would be similar to (some variables have different names):
// dummy data
var transDoc = XDocument.Parse(#"
<root name='rootAttribute'>
<OrderRequest name='one' />
<OrderRequest name='two' />
<OrderRequest name='three' />
</root>");
var xmlDoc = XDocument.Parse("<ReplyDocument />");
xmlDoc.Root.Add(
transDoc.Root.Elements("OrderRequest").Select(o =>
new XElement("ConfirmationElement",
new XAttribute("name", (string)o.Attribute("name")),
new XElement("ItemDetail"))));
Both examples output:
<ReplyDocument>
<ConfirmationElement name="one">
<ItemDetail />
</ConfirmationElement>
<ConfirmationElement name="two">
<ItemDetail />
</ConfirmationElement>
<ConfirmationElement name="three">
<ItemDetail />
</ConfirmationElement>
</ReplyDocument>