0
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
    <meta name="Generator"/>
  </head>
  <body>
    <h1>My head 1</h1>
  </body>
</html>

上記は、XElementオブジェクトの.ToStringですhtml。いいね。

ボディのinnerXmlを取得しようとしていますが、XPathがnullを返します。

XElement html = GettheHTMLAsXElementCorrectly()
var whyIsThisNull =  html.XPathSelectElement("/html/body");
4

2 に答える 2

3

名前空間が使用されるときはいつでも(あなたの場合は<html>)、ノードを検索するときに名前空間を定義する必要があります。

LINQ to XMLの使用
(私の意見では、より簡単でクリーンなソリューション)

// Create a XNamespace instance for the default namespace
XNamespace xhtml = "http://www.w3.org/1999/xhtml";

// Select the node using LINQ to XML
var bodyByLinq = doc.Element(xhtml + "html").Element(xhtml + "body");

XPathの使用

// Create a namespace manager
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());

// Define your default namespace including a prefix to be used later in the XPath expression
namespaceManager.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");

// Select the node using XPath
var bodyByXPath = doc.XPathSelectElement("/xhtml:html/xhtml:body", namespaceManager);

更新:提供された例が正しくなかったため、私の答えを改善しました

于 2012-08-13T22:57:51.310 に答える
0

@zombiehunter は正しいので、彼にクレジットを与えました。

私もこの方法を試しました.XPathが名前空間を無視することを伝えました. も機能するようです。

var notNullAnyMore =  html.XPathSelectElement("//*[local-name() = 'body']" );
于 2012-08-13T23:09:17.400 に答える