I am trying to figure out how to group XML nodes with the same name but different values.
The web service I’m using returns an XmlElement that looks like this:
<Items>
<Item>
<Name name="Name">Item 1</Name>
<Description name="Description">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</Description>
<AssociatedItems name="Associated Items">Item 2</AssociatedItems>
<AssociatedItems name="Associated Items">Item 3</AssociatedItems>
<AssociatedItems name="Associated Items">Item 4</AssociatedItems>
<AssociatedItems name="Associated Items">Item 5</AssociatedItems>
</Item>
</Items>
I am transforming each node into an HTML tag
protected void lnkItem_Click(object sender, EventArgs e)
{
LinkButton link = (LinkButton)sender;
GridViewRow row = (GridViewRow)link.Parent.Parent;
string id = gv.DataKeys[row.RowIndex]["id"].ToString();
PublicApiAsmxServiceSoapClient service = new PublicApiAsmxServiceSoapClient("PublicApiAsmxServiceSoap", WEB_SERVICE_URL);
XmlElement xml = service.ItemGetAsXml(id);
XElement nodes = XElement.Parse(xml.InnerXml);
foreach (var node in nodes.Elements())
{
InsertHTML(node);
}
}
private void InsertHTML(XElement node)
{
if (node.Value == string.Empty)
return;
pnl.ContentTemplateContainer.Controls.Add(new LiteralControl(String.Format("<h3>{0}</h3>", node.Attribute("name").Value)));
pnl.ContentTemplateContainer.Controls.Add(new LiteralControl(String.Format("<p>{0}</p>", node.Value)));
}
With my code right now, the HTML output would be:
<h3>Name</h3>
<p>Item 1</p>
<h3>Description</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h3>Associated Items</h3>
<p>Item 2</p>
<h3>Associated Items</h3>
<p>Item 3</p>
<h3>Associated Items</h3>
<p>Item 4</p>
<h3>Associated Items</h3>
<p>Item 5</p>
Is there a way to group the same nodes as an unordered list? Something like this, perhaps:
<h3>Name</h3>
<p>Item 1</p>
<h3>Description</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h3>Associated Items</h3>
<ul>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
Thank you! (Please be nice.)
PS
The child nodes that repeat aren’t limited to AssociatedTerms only. There are possibly more child nodes of the same name that repeat.
It would be easiest using a generator to generate the elements based on the groupings since what gets generated depends on how many duplicates there are.
As I understand it, you’re grouping by element name and the value of the
nameattributes. Then generating anh3followed by an element depending on if there are multiple elements in the group.pif there’s a single element or aulif there are multiple elements.Yields the following: