在XML文件中的命名空间真的让人烦,因为在读取节点时采用SelectSingleNode方法直接读取会返回一个null。
看了网上很多文章,基本都是要求添加一个XmlNamespaceManager,然后在SelectSingleNode方法中加入该XmlNamespaceManager。
但我按照这个方法操作了,结果还是不行,不知道是我的问题,还是网友写错了,又或者是C#同.NET的差异(我用的是ASP.NET)。过程真的是煞费苦心。。。郁闷的够呛。
后面又看了下相关的网络文件,并实验后,发现除了以上操作外,还必须在XPATH的每个路径节点前添加命名空间,真的是很繁琐啊。具体示例如下:
1。原始XML文件:test3.xml
<TableCell xmlns="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
<ReportItems>
<Textbox Name="textbox5">
<Style>
<FontFamily>aa</FontFamily>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
<ZIndex>1</ZIndex>
<CanGrow>true</CanGrow>
<Value />
</Textbox>
</ReportItems>
</TableCell>
2.检索节点的处理程序示例:
XmlDocument sourceDoc = new XmlDocument();
string path = Server.MapPath("test3.xml");
sourceDoc.Load(path);
XmlNamespaceManager xmlman = new XmlNamespaceManager(sourceDoc.NameTable);
xmlman.AddNamespace("ns", "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner");
XmlNode style = sourceDoc.SelectSingleNode("/ns:TableCell/ns:ReportItems/ns:Textbox/ns:Style", xmlman);
for (int i = 0; i < style.ChildNodes.Count; i++)
{
XmlNode value = style.ChildNodes[i];//SelectSingleNode("ReportItems/Textbox/Value",xmlman);
value.InnerText = "新内容";
}
sourceDoc.Save(Server.MapPath("bb.xml"));
另外,如果XML文件结构固定,也可以用如下方法获取节点,省了命名空间的问题:
XmlNode style = sourceDoc.ChildNodes[0].ChildNodes[0].ChildNodes[0];
不知道各位朋友对于ASP.NET下的带XMLNS的XML文件处理有什么好的方法。