1

我正在做一个使用 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);
}

我认为我的代码有问题。谁能帮助我?谢谢你。

4

1 回答 1

0

只是一个想法 - 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/NewDataSet/Toy[ID=1]/Comments/Comment应用于原始文档的 xpath 应该可以正常工作。

于 2013-08-18T12:16:25.347 回答