XPath 查询问题

neodotnet 2004-08-18 09:54:42
我有一XML文件, 使用了一个默认的名字空间, 所以我在用 SelectNodes()查询时, 要求必须要有 XmlNameSpaceManager nsmgr, 我于是给 默认名字空间起了个前缀, 加到 nsmgr 中。这样在用 XPath 查询时,每个节点前必须要加这个前缀, 感觉很麻烦。有没有什么办法不用加这个前缀。

还有, 每当我添加一个前点时, 都会在新的节点上添加一个空的名字空间, 如下所示,

<newElement xmlns="">...</newElement>

这又是什么原因呢? 能不能不让这个空名字空间出现呢?

多谢
...全文
142 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
neodotnet 2004-08-18
  • 打赏
  • 举报
回复
“lexchou(本人已死)==(有事烧纸) ”的方案的结果如下:

<root xmlns="http://neo.net">
<child xmlns="http://neo.net" />
</root>

虽然这样的代码可以通过 XSD 的验证,但是我需要的是下面的,而且“有事烧纸”的代码也不够简单
<root xmlns="http://neo.net">
<child />
</root>
neodotnet 2004-08-18
  • 打赏
  • 举报
回复
我的理解是思归大哥的方法是手工向里面写新节点的 xml 代码, 不过我有很多同级的子节点,感觉这样就不太方便了。

不过大哥的思考方式小弟学到了。受益非浅!
lexchou 2004-08-18
  • 打赏
  • 举报
回复
XmlNode xmlns=doc.CreateAttribute("xmlns");
XmlNode Node=doc.CreateElement("Node");
xmlns.Value="http://xxxxxxxxx";
Node.Attributes.SetNamedItem(xmlns);
MessageBox.Show(Node.OuterXml);

未测试,默认命名空间声明和普通属性一样创建
saucer 2004-08-18
  • 打赏
  • 举报
回复
not srue if there is another better way, but try

string s = "<root xmlns='http://neo.net' />";
XmlDocument doc = new XmlDocument();
doc.LoadXml(s);

doc.DocumentElement.InnerXml = "<child/>";

doc.DocumentElement["child"].InnerXml = "<grandchild />";
doc.Save(Console.Out);
neodotnet 2004-08-18
  • 打赏
  • 举报
回复
牛XX 的思归大哥又出现了, 我得抓紧机会

大哥的第一个问题小弟看懂了, 下面是我第二个问题 Code:

string s = "<root xmlns='http://neo.net' />";
XmlDocument doc = new XmlDocument();
doc.LoadXml(s);

XmlElement xe = doc.CreateElement("child");
doc.DocumentElement.AppendChild(xe);
doc.Save(Console.Out);

输出结果是:

<root xmlns="http://neo.net">
<child xmlns="" />
</root>

能不能不让那个 xmlns="" 出现呢?即
<root xmlns="http://neo.net">
<child />
</root>
上面是我想要的

我用下面的方法可以达到我需要的结果,但是感觉不爽, 有没有其他方法?
string s = "<root xmlns='http://neo.net' />";
XmlDocument doc = new XmlDocument();
doc.LoadXml(s);

// 注意这句不同
XmlElement xe = doc.CreateElement("child", "http://neo.net");
doc.DocumentElement.AppendChild(xe);
doc.Save(Console.Out);

saucer 2004-08-18
  • 打赏
  • 举报
回复
1. the documentation for XmlNode.SelectNodes says

Note
If the XPath expression does not include a prefix, it is assumed that the namespace URI is the empty namespace. If your XML includes a default namespace, you must still add a prefix and namespace URI to the XmlNamespaceManager; otherwise, you will not get any nodes selected.

2. how did you create the nodes? show some code?

string s = "<root xmlns='' />";
XmlDocument doc = new XmlDocument();
doc.LoadXml(s);

XmlElement xe = doc.CreateElement("child");
doc.DocumentElement.AppendChild(xe);
doc.Save(Console.Out);

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧