C# Xpath 命名空间匹配

最近做项目需用报表功能,因此采用vs 内置的报表控件ReportViewer

由于报表部分列需动态生成,不得不用操作xml的方法修改rdlc文件


编写read方法 

     public static string Read(string path, string node, string attribute)
        {
            string value = "";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("ns", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition");
                XmlNode xn = doc.SelectSingleNode(node, nsmgr);
                value = (attribute.Equals("") ? xn.InnerText : xn.Attributes[attribute].Value);
            }
            catch { }
            return value;
        }



节点定位示例  XmlHelper.Read(path, "//ns:TablixRows/ns:TablixRow[1]/ns:TablixCells", "")

由于该xml有命名空间,所以Xpath 匹配也需添加命名空间

对于多命名空间xml ,添加节点时应指明空间名

    public void Insert(string node, string element, string attribute, string value,string NamespaceURI)
        {
            try
            {
                XmlNode xn = doc.SelectSingleNode(node, nsmgr);
                if (element.Equals(""))
                {
                    if (!attribute.Equals(""))
                    {
                        XmlElement xe = (XmlElement)xn;
                        xe.SetAttribute(attribute, value);
                    }
                }
                else
                {
                    XmlElement xe = doc.CreateElement(element, NamespaceURI);
                    if (attribute.Equals(""))
                        xe.InnerText = value;
                    else
                        xe.SetAttribute(attribute, value);
                    xn.AppendChild(xe);
                }
            }
            catch { }
        }



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值