XML格式字符串 与 FarPoint互转

string Col1 = "列1", Col2 = "列2";
string parentName = "parent";// xml的父节点
string eleName = "element";// xml子节点

// 把xml字符串载入到farpoint
private void XmlToFarPoint(FarPoint.Win.Spread.SheetView sheet, string xmlString)
{
    XmlDocument document = new XmlDocument();
    document.LoadXml(xmlString);
    XmlNodeList list = document.SelectNodes(string.Format("/{0}/{1}", this.parentName, this.eleName));
    int rowCount = 0;
    foreach (XmlElement element in list)
    {
        if (rowCount >= this.wFpSpread1_Sheet1.RowCount)
        {
             // 保存的行数可能会比新的表格行数大
             break;
        }
        sheet.Cells[rowCount, 1].Text = element.GetElementsByTagName(Col1)[0].InnerText;
        sheet.Cells[rowCount, 2].Text = element.GetElementsByTagName(Col2)[0].InnerText;
        // 其它列……
        rowCount++;
    }
}


// 获取表格数据,组合成xml字符串返回
private string FarPointToXml(FarPoint.Win.Spread.SheetView sheet)
{
    XmlDocument document = new XmlDocument();
    XmlDeclaration xmldecl = document.CreateXmlDeclaration("1.0", "utf-8", null);
    XmlElement root = document.DocumentElement;
    document.InsertBefore(xmldecl, root);


    XmlElement parent = document.CreateElement(this.parentName);
    document.AppendChild(parent);

    for(int row = 0; row < sheet.RowCount; row++)
    {
        XmlElement element = document.CreateElement(this.eleName);

        XmlElement number = document.CreateElement(Col1);
        number.InnerText = sheet.Cells[row, 1].Text;
        element.AppendChild(number);

        XmlElement descript = document.CreateElement(Col2);
        descript.InnerText = sheet.Cells[row, 2].Text;
        element.AppendChild(descript);
        // 其它列……


        parent.AppendChild(element);
    }

    return document.InnerXml;
}

 

xml文件字符串如下



    
        <列1>1
        <列2>测试
    
    
        <列1>2
        <列2>测试
    

 

你可能感兴趣的:(C#)