对于XSL文档,XElementObj.Root.Element(“anything”)始终为null

时间:2011-12-21 02:17:14

标签: .net xml

我在使用POX的tracer-bullet版本中的代码一切顺利,但后来我添加了XSL,我再也无法使用.Element("anything")

这是我的xml文档:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="*|@*">
  <xsl:apply-templates select="*|@*" />
 </xsl:template>
 <xsl:template match="CO">
  <html>
   <head>
    <title>My Page</title>
   </head>
   <body></body>
  </html>
 </xsl:template>
</xsl:stylesheet>

抛出空引用异常:

templateDoc.Root.Element("body").Add(newElements);

因为.Element("body")为空。 templateDoc是一个XDocument对象,使用以下方法正确加载了上述XML:XDocument.Load(filePath);

为了能够在这里找到身体节点,我需要做什么?

1 个答案:

答案 0 :(得分:1)

您需要指定名称空间。

  XDocument doc = XDocument.Load(file);
  XNamespace ns = "http://www.w3.org/1999/XSL/Transform";

  var result = from ele in doc.Descendants(ns + "stylesheet").Descendants("html")
                select ele;

OR

    var result = (from ele in doc.Descendants(ns + "stylesheet").Descendants("body")
                 select ele).FirstOrDefault();

    if (result != null)
    {

        result.Add(new XElement("p", "Hello World"));
        doc.Save(file);
    }