我有一个XML文件,我必须从中提取标签中的属性值。这种结构中的XML类型
<customer>
<customerMiddleInitial>W</customerMiddleInitial>
<name>
<FirstName>XXXXXXXX</FirstName>
<LastName> YYYYYYYY</LastName>
</name>
<customerBirth>1983-01-01</customerBirth>
<customerWorkPhone>020 1234567</customerWorkPhone>
<customerMobilePhone>0799 1234567</customerMobilePhone>
<previousCust>0</previousCust>
<timeOnFile>10</timeOnFile>
<customerId>CUST123</customerId>
</customer>
所以,我想提取标签之间的所有细节。预期的输出应该是所有客户的详细信息。
我如何在C#中实现这一点? 任何帮助将不胜感激。
答案 0 :(得分:0)
XmlDocument DOC = new XmlDocument();
DOC.Load("LoadYourXMLHere.xml");
XmlNodeList ParentNode = DOC.GetElementsByTagName("customer");
foreach (XmlNode AllNodes in ParentNode)
{
if (ParentNode == DOC.GetElementsByTagName("customerMiddleInitial"))
{
customer.Initial = AllNodes["customerMiddleInitial"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("name"))
{
customer.FirstName= AllNodes["FirstName"].InnerText;
customer.LastName= AllNodes["LastName"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("customerBirth"))
{
customer.Birthdate= AllNodes["customerBirth"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("customerWorkPhone"))
{
customer.WorkPhone= AllNodes["customerWorkPhone"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("customerMobilePhone"))
{
customer.MobilePhone = AllNodes["customerMobilePhone"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("previousCust"))
{
customer.PreviousCust= AllNodes["previousCust"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("timeOnFile"))
{
customer.TimeOnFile= AllNodes["timeOnFile"].InnerText;
}
if (ParentNode == DOC.GetElementsByTagName("customerId"))
{
customer.ID= AllNodes["customerId"].InnerText;
}
}
创建Customer模型并在C#中执行上述xml解析。
此致
Thiyagu Rajendran
**如果答案有帮助,请将答复标记为答案,如果不答复,请将其标记为
。答案 1 :(得分:0)
首先,您需要看到此answer
当你generated模型只需使用此代码将反序列化的xml转换为object.And之后只需使用模型来处理数据。这很简单
public static T FromXml<T>(String xml)
{
T returnedXmlClass = default(T);
try
{
using (TextReader reader = new StringReader(xml))
{
try
{
returnedXmlClass =
(T)new XmlSerializer(typeof(T)).Deserialize(reader);
}
catch (InvalidOperationException)
{
// String passed is not XML, simply return defaultXmlClass
}
}
}
catch (Exception ex)
{
}
return returnedXmlClass;
}
并使用
var model = FromXml<customer>(yourXmlString);