以下は、デフォルトの名前空間 XPath です。
private static XElement XPathSelectElementDefaultNamespace(XDocument document,
string element)
{
XElement result;
string xpath;
var ns = document.Root.GetDefaultNamespace().ToString();
if(string.IsNullOrWhiteSpace(ns))
{
xpath = string.Format("//{0}", element);
result = document.XPathSelectElement(xpath);
}
else
{
var nsManager = new XmlNamespaceManager(new NameTable());
nsManager.AddNamespace(ns, ns);
xpath = string.Format("//{0}:{1}", ns, element);
result = document.XPathSelectElement(xpath, nsManager);
}
return result;
}
使用法:
string xml1 = @"<root>
<hello></hello>
</root>";
string xml2 = @"<root xmlns=""namespace"">
<hello></hello>
</root>";
var d = XDocument.Parse(xml1);
Console.WriteLine(XPathSelectElementDefaultNamespace(d, "hello"));
// Prints: <hello></hello>
d = XDocument.Parse(xml2);
Console.WriteLine(XPathSelectElementDefaultNamespace(d, "hello"));
// Prints: <hello xmlns="namespace"></hello>