C#,xml、html节点数据解析

/// 
/// 节点数据解析示例
/// 
public static void example()
{
    string data = "...  审核者 操作 创建 指派给  ..."
            
    string thead = Tool.getNode(data, "thead");     //获取...节点数据
    List head = Tool.getNodes(thead, "th"); //获取所有...节点数据: "审核者"、"创建"、"创建"、"指派给"

    string data3 = "";
    string Node = Tool.trimNode(data3, new string[] { "div", "a" }); // Node = "所属项目";
}
#region xml、html节点数据解析

/// 
/// 获取指定串值对的数据, start = , end = 
/// 
public static string subString(string data, string start, string end)
{
    try
    {
        int i1 = data.IndexOf(start) + start.Length, i2 = data.IndexOf(end, i1);
        string tmp = data.Substring(i1, i2 - i1);

        return tmp;
    }
    catch (Exception) { return null;  }
}

/// 
/// 获取指定串值对的数据, 从开始寻找start = , 从结尾寻找end = 
/// 
public static string subStringE(string data, string start, string end)
{
    try
    {
        int i1 = data.IndexOf(start) + start.Length, i2 = data.LastIndexOf(end);
        string tmp = data.Substring(i1, i2 - i1);

        return tmp;
    }
    catch (Exception) { return null; }
}

/// 
/// 获取节点的数据, node为节点名称
/// 
public static string getNode(string data, string nodeName)
{
    try
    {
        data = subString(data, "<" + nodeName, "/" + nodeName + ">");
        data = subStringE(data, ">", "<");

        return data.Trim();     // 去除首位空格
    }
    catch (Exception) { return null; }
}

/// 
/// 获取节点对应的所有节点数据, node为节点名称
/// 
public static List getNodes(string data, string nodeName)
{
    List Nodes = new List();

    try
    {
        int pos = 0;
        while (pos != -1)
        {
            string tmp = getNode(data, nodeName);// 获取第一个节点数据
            if (tmp == null) break;
            Nodes.Add(tmp);

            string end = "/" + nodeName + ">";
            pos = data.IndexOf(end) + end.Length;// 记录当前解析的最后位置
            data = data.Substring(pos);          // 删除已解析部分
        }
    }
    catch (Exception) { }
    return Nodes;

}

/// 
/// 从节点node中提取子节点nodeName中的数据,无此子节点则原样返回
/// 
public static string trimNode(string node, string[] nodeName)
{
    string tmp = node;
    foreach (string name in nodeName) if (tmp.Contains("<" + name)) tmp = Tool.getNode(tmp, name);
    return tmp;
}

/// 
/// 从节点数组nodes中提取子节点nodeName中的数据,无此子节点则原样返回
/// 
public static List getTrimNodes(List nodes, string[] nodeName)
{
    List Nodes = new List();
    foreach (string node in nodes) Nodes.Add(trimNode(node, nodeName));
    return Nodes;
}

#endregion

xml数据解析示例,java https://git.oschina.net/scimence/xmlAnalysis


你可能感兴趣的:(C#,xml,html节点数据解析)