XElementObj.Root.Element( "anything" ) 对于 XSL 文档始终为空



我的代码在使用POX的跟踪子弹版本中一切都很好,但是后来我添加了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);

我需要做什么才能找到这里的身体节点?

需要指定命名空间

  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;

    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);
    }

最新更新