C#开发中获取XML节点值,XML转对象案例

一、获取XML节点值

string strMsg="XML内容";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strMsg);

// 创建命名空间管理器
XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
nsManager.AddNamespace("ns1", "http://webservice.app.bizinterface.custom.eas.kingdee.com");

// 调试输出,查看 XML 结构
Console.WriteLine("XML 结构:");
Console.WriteLine(xmlDoc.InnerXml);

// 查找rspCode和rspMsg的节点
XmlNode rspCodeNode = xmlDoc.SelectSingleNode("//rspCode", nsManager);
XmlNode rspMsgNode = xmlDoc.SelectSingleNode("//rspMsg", nsManager);


// 提取内容
string rspCode = rspCodeNode?.InnerText;
string rspMsg = rspMsgNode?.InnerText;

二、XML转对象案例

string strMsg="xml内容";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strMsg);

// 创建命名空间管理器
XmlNamespaceManager nsManager = new XmlNamespaceManager(xmlDoc.NameTable);
nsManager.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
nsManager.AddNamespace("ns1", "http://webservice.app.bizinterface.custom.eas.kingdee.com");

// 调试输出,查看 XML 结构
Console.WriteLine("XML 结构:");
Console.WriteLine(xmlDoc.InnerXml);

// 查找rspCode和rspMsg的节点
XmlNode getAPaymentBillsReturn = xmlDoc.SelectSingleNode("//getAPaymentBillsReturn", nsManager);
string vAPaymentBillsReturn = getAPaymentBillsReturn?.InnerXml;

var lstBills = ConvertToObject(vAPaymentBillsReturn);



// 公共方法将XML字符串转换为对象
public static XMLDATA ConvertToObject(string xmlData)
{
    XMLDATA data;
    XmlSerializer serializer = new XmlSerializer(typeof(XMLDATA));
    using (System.IO.StringReader reader = new System.IO.StringReader(xmlData))
    {
        data = (XMLDATA)serializer.Deserialize(reader);
    }
    return data;
}



[XmlRoot(ElementName = "XMLDATA")]
public class XMLDATA
{
    [XmlElement(ElementName = "bill")]
    public List<Bill> Bills { get; set; }
}


// 定义类来映射XML结构
[XmlRoot(ElementName = "bill")]
public class Bill
{
    [XmlElement(ElementName = "billNumber")]
    public string BillNumber { get; set; }

    [XmlArray(ElementName = "entrys")]
    [XmlArrayItem(ElementName = "entry")]
    public List<Entry> Entrys { get; set; }
}

// 定义类来映射XML结构
[XmlRoot(ElementName = "entry")]
public class Entry
{
    /// <summary>
    /// 付审单编码
    /// </summary>
    [XmlElement(ElementName = "payRequestBillNo")]
    public string PayRequestBillNo { get; set; }
}

上一篇:IDEA连接SqlServer数据库


下一篇:MySQL InnoDB引擎-存储结构