从XML文档中提取节点

时间:2016-08-02 18:25:35

标签: c# xml linq nodes

我有这个XML:

<WMFWUpload>
         <Date></Date>
         <GroupIndex></GroupIndex>
         <Id></Id>
         <NumGroups></NumGroups>
         <NumRecs></NumRecs>
         <Receipts>
            <Receipt>
               <CreationDateTimeStamp></CreationDateTimeStamp>
               <CreationProcessStamp></CreationProcessStamp>
               <DateTimeStamp></DateTimeStamp>
               <InterfaceRecordId />
               <ProcessStamp></ProcessStamp>
               <UserStamp></UserStamp>
            </Receipt>
         </Receipts>
</WMFWUpload>

我从路径中读取文档,我只想选择Recepit节点,但不仅仅是节点的值,结果应该是:

<Receipt>
    <CreationDateTimeStamp></CreationDateTimeStamp>
    <CreationProcessStamp></CreationProcessStamp>
    <DateTimeStamp></DateTimeStamp>
    <InterfaceRecordId />
    <ProcessStamp></ProcessStamp>
    <UserStamp></UserStamp>
</Receipt>

到目前为止,这是我的代码,我被困住了。

  XDocument doc = XDocument.Load(@"C:\Users\Daniel\Documents\Pite\Selmec\WorkingData\Origen\ReceivingUpload.xml");
            var query = from c in doc.Descendants("Receipt").DescendantsAndSelf().ToList() select c;

            foreach (var value in query)
            {
                Console.WriteLine(value);
            }

            Console.ReadLine();

1 个答案:

答案 0 :(得分:0)

使用此

var query = doc.Descendants("Receipt");
string s = string.Concat(query);

<强>更新

确保在xml文件

上放置此行<?xml version="1.0" encoding="utf-8"?>

我使用过这个xml

<?xml version="1.0" encoding="utf-8"?>
<WMFWUpload>
         <Date></Date>
         <GroupIndex></GroupIndex>
         <Id></Id>
         <NumGroups></NumGroups>
         <NumRecs></NumRecs>
         <Receipts>
            <Receipt>
               <CreationDateTimeStamp></CreationDateTimeStamp>
               <CreationProcessStamp></CreationProcessStamp>
               <DateTimeStamp></DateTimeStamp>
               <InterfaceRecordId />
               <ProcessStamp></ProcessStamp>
               <UserStamp></UserStamp>
            </Receipt>
         </Receipts>
</WMFWUpload>