简体   繁体   English

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

[英]How to extract a part of xml code from an xml file using c# code

 <?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>

How can I extract the portion 如何提取部分

 <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>

from the above xml file. 从上面的xml文件中。

I need the c# code to extract a part of xml tag from an xml file. 我需要c#代码从xml文件中提取xml标记的一部分。

If the file isn't too big (smaller than a few MB), you can load it into an XmlDocument : 如果文件不是太大(小于几MB),则可以将其加载到XmlDocument

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

and then you can parse for the <Header> element using an XPath expression: 然后可以使用XPath表达式解析<Header>元素:

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

You can use XPath like in this tutorial: 您可以像本教程中一样使用XPath:

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

Use Linq-to-xml: 使用Linq-to-xml:

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

Linq version Linq版本

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM