如何使用linq为xml文件添加命名空间



我正在加载这样一个xml文件:

XDocument xDoc = XDocument.Load("test.xml");

这个test.xml文件有类似<o:abc> <o:bcd>的节点但是没有申报。我试着用这个:

XDocument xDoc = XDocument.Load("C:\Documents and Settings\c0kohka\Desktop\test.xml");
XNamespace o = "http:\abc.html" ;

它不工作给出错误前缀0未声明。有人能告诉我怎么做吗?

听起来您的XML是无效的。

XML文档中的命名空间必须在文档中通过在父元素上写入xmlns:o="http://...来声明

一旦您定义了您的XNamespace,您需要使用它:

XDocument xDoc = XDocument.Load("C:\Documents and Settings\c0kohka\Desktop\test.xml");
XNamespace o = "http:\abc.html" ;  // this seems odd - usually, this would be o = "http://abc.company.com" or something
XElement someElement = xDoc.Descendants(o + "SomeElement");

或类似的东西-没有看到XML它充其量只是猜测....

您的。xml文件无效。所以你必须"修复"你的。xml文件,而不是其他任何东西。

最新更新