如何使用c#代码从xml文件中提取部分xml代码

时间:2011-02-14 05:39:17

标签: c# xml

 <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
 <eRecon xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="eRecon.xsd">
 <Header>
  <Company Code="" /> 
  <CommonCarrierCode /> 
  <InputFileName InputIDPk="">F:\ReconNew\TmesysRec20100111.rec</InputFileName> 
  <BatchNumber>000152</BatchNumber> 
  <InputStartDateTime>2010-02-26 11:47:00</InputStartDateTime> 
  <InputFinishDateTime>2010-02-26 11:47:05</InputFinishDateTime> 
  <RecordCount>8</RecordCount> 
  </Header>
 <Detail>
  <CarrierStatusDate>2010-01-11</CarrierStatusDate> 
  <ClaimNum>YDF02892 C</ClaimNum> 
  <InvoiceNum>0108013775</InvoiceNum> 
  <LineItemNum>001</LineItemNum> 
  <NABP>10600211</NABP> 
  <RxNumber>4695045</RxNumber> 
  <RxDate>2008-07-21</RxDate> 
  <CheckNum /> 
  <PaymentStatus>PENDING</PaymentStatus> 
  <RejectDescription /> 
  <InvoiceChargeAmount>152.15</InvoiceChargeAmount> 
  <InvoicePaidAmount>131.00</InvoicePaidAmount> 
 </Detail>
 </eRecon>

如何提取部分

 <Header>
  <Company Code="" /> 
  <CommonCarrierCode /> 
  <InputFileName InputIDPk="">F:\ReconNew\TmesysRec20100111.rec</InputFileName> 
  <BatchNumber>000152</BatchNumber> 
  <InputStartDateTime>2010-02-26 11:47:00</InputStartDateTime> 
  <InputFinishDateTime>2010-02-26 11:47:05</InputFinishDateTime> 
  <RecordCount>8</RecordCount> 
 </Header>

来自上面的xml文件。

我需要c#代码从xml文件中提取部分xml标记。

4 个答案:

答案 0 :(得分:4)

如果文件不是太大(小于几MB),您可以将其加载到XmlDocument

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\yourfile.xml");

然后您可以使用XPath表达式解析<Header>元素:

XmlNode headerNode = doc.SelectSingleNode("/eRecon/Header");
if(headerNode != null)
{
    string headerNodeXml = headerNode.OuterXml;
}

答案 1 :(得分:0)

您可以像本教程中一样使用XPath:

http://www.codeproject.com/KB/cpp/myXPath.aspx

答案 2 :(得分:0)

使用Linq-to-xml:

XDocument xmlDoc = XDocument.Load(@"c:\sample.xml");
var header = xmlDoc.Descendants("Header").FirstOrDefault();

答案 3 :(得分:0)

Linq版

string fileName=@"d:\xml.xml";
var descendants = from i in XDocument.Load(fileName).Descendants("Header")
select i;