关于XML解析的几个实用方法

 1 获取XML文件的路径

protected   static  String ServerRoot()
    
{
        
return HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath).TrimEnd('/');
    }

2 将XML中的所有节点用一定规则将所有的节点组装成一个String,可以在不同节点元素之间加入一个符号. 便于以后处理的时候用split()方法处理,放入一个数组里面,这样操作XML各个节点就变换成操作一个数组了。

  private   static  String ShowXML(XmlNodeList nodeList)
    
{
        String strReturn 
= "";

        
foreach (XmlNode node in nodeList)
        
{
            
if (node.NodeType != XmlNodeType.Comment)
            
{
                
if (node.HasChildNodes)
                
{
                    
foreach (XmlNode nn in node.ChildNodes)
                    
{
                        strReturn 
+= nn.InnerText;

                        strReturn 
+= "*";
                    }

                }


                
//strReturn = strReturn.Substring(0, strReturn.Length - 1);

                
//不同节点之间
                strReturn += "?";
            }

        }


        strReturn 
= strReturn.Substring(0, strReturn.Length - 1);

        
return strReturn;
    }

//  指定XML文件路径,获得节点值
     private   static  String GetByPath(String strPath, String strKey)
    
{
        XmlDocument xDoc 
= null;
        String strReturn 
= "";

        
try
        
{

            xDoc 
= new XmlDocument();

            xDoc.Load(strPath);

            XmlElement xElem 
= (XmlElement)(xDoc.SelectSingleNode(strKey));

            
if (xElem != null)
            
{
                String str 
= xElem.InnerText.Replace(" """);

                strReturn 
= str.Trim();
            }

        }

        
catch (Exception e)
        
{
            String str 
= e.Message;

            strReturn 
= "";
        }


        
finally
        
{
            xDoc 
= null;
        }


        
return strReturn;
    }

4

//  指定路径,获得指定节点及其所有子节点的值(暂时用于Style的读取)
     private   static  String GetAllByPath(String strPath, String strKey)
    
{
        XmlDocument xDoc 
= null;
        String strReturn 
= "";

        
try
        
{
            xDoc 
= new XmlDocument();

            xDoc.Load(strPath);

            XmlElement xElem 
= (XmlElement)(xDoc.SelectSingleNode(strKey));

            
if (xElem != null)
            
{
                XmlNodeList nodeList 
= xElem.ChildNodes;

                strReturn 
= ShowXML(nodeList);
            }

        }

        
catch (Exception e)
        
{
            String str 
= e.Message;
        }


        
return strReturn;
    }
指定XML文件路径,获得节点值. 每次获得单独的一个节点值,所以也不需要什么规则来组装一个string。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值