在xml中为所选节点选择comments元素

本文关键字:节点 选择 comments 元素 xml | 更新日期: 2023-09-27 18:28:00

我正在做一个使用XML文件的博客。我想用ListView显示所选帖子的评论。这是我的XML文件:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<NewDataSet>
<Toy>
<ID>1</ID>
<Type>Despicable Me</Type>
<Character>Agnes Gru</Character>
<Description>Agnes, like her sisters, wished to be adopted by someone who cared about her.
At first, Agnes is only one out of the three sisters to be excited to be adopted by Gru. 
 She happily hugs his leg and plays games with him, whereas her sisters are gawping at  
 Gru, their dream of the 'perfect parents' in tatters. 
She is unaware of Gru's own dislike of the whole adoption, her innocence prevailing. 
She is a very naive and innocent child, which is why Margo is so protective of her. 
She thinks Gru's dog is cute and chases after him, despite some protest from Margo.
  </Description>
<Picture>agnes.jpg</Picture>
 <Comments>
  <Comment>
    It's a very cute little girl!
  </Comment>
  <Comment>
    It's a very cute little girl!
  </Comment>
</Comments>
 </Toy>
</NewDataSet>

这是我的xsl文件:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:template match="NewDataSet">
<NewDataSet>
  <xsl:apply-templates/>
 </NewDataSet>
 </xsl:template>
<xsl:template match="Toy/Comments">
 <Toy>
  <Comments>
    <xsl:for-each select="*">
      <xsl:attribute name="{name()}">
        <xsl:value-of select="text()"/>
      </xsl:attribute>
    </xsl:for-each>
  </Comments>
 </Toy>
</xsl:template>
</xsl:stylesheet>

下面是我的代码:(我已成功通过会话)

protected void Page_Load(object sender, EventArgs e)
{
String ID = Session["ID"].ToString(); 
XmlDataSource2.XPath = String.Format("/NewDataSet/Toy[@ID='{0}']/Comments",ID);
}

我认为我的代码有问题。有人能帮我吗?非常感谢。

在xml中为所选节点选择comments元素

只是一个想法-ID是一个元素,但在XPath中,您将其视为属性(@ID)。尝试将/NewDataSet/Toy[@ID='{0}']/Comments更改为/NewDataSet/Toy[ID='{0}']/Comments

编辑:这是你转换的结果

<?xml version="1.0" encoding="UTF-8"?><NewDataSet>1Despicable MeAgnes GruAgnes, like her sisters, wished to be adopted by someone who cared about her.
At first, Agnes is only one out of the three sisters to be excited to be adopted by Gru. 
 She happily hugs his leg and plays games with him, whereas her sisters are gawping at  
 Gru, their dream of the 'perfect parents' in tatters. 
She is unaware of Gru's own dislike of the whole adoption, her innocence prevailing. 
She is a very naive and innocent child, which is why Margo is so protective of her. 
She thinks Gru's dog is cute and chases after him, despite some protest from Margo.
  agnes.jpg<Toy><Comments Comment="&#xA;    It's a very cute little girl!&#xA;  "/></Toy></NewDataSet>

正如您所看到的,您几乎丢失了所有的标记。此外,ID元素已经消失,所以您的xpath无法返回任何数据,因为没有具有元素ID的Toy元素。

我不知道你到底想对xslt做什么——你应该详细说明。

但是我不明白为什么需要转换输入xml。IMO在原始文档上应用的xpath /NewDataSet/Toy[ID=1]/Comments/Comment应使其工作。