我试图弄清楚如何对具有相同名称但不同值的 XML 节点进行分组。
我正在使用的 Web 服务返回一个如下所示的 XmlElement:
<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>
我正在将每个节点转换为 HTML 标记
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)));
}
现在使用我的代码,HTML 输出将是:
<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>
有没有办法将相同的节点分组为无序列表?像这样的东西,也许:
<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>
谢谢!(请友好一点。)
PS 重复的子节点不仅限于 AssociatedTerms。可能有更多重复的同名子节点。