Xelement从不同的文件中提取xml并组合回xml

本文关键字:xml 提取 组合 文件 Xelement | 更新日期: 2023-09-27 18:26:36

我有这个XML。我想按订单号="00070853"找到第一个/摘录第一个在C#中,然后与其他文件中的相同xml组合相同的模式。我试过(只是为了提取,但知道如何组合也很好)

      IEnumerable<XElement> orderXml = from el in xdoc.Descendants(ns + "order")
      where (string)el.Attribute(ns + "order-no").Value == badOrder
      select el;

下面是示例xml(它也有我想要的模式)

      <?xml version="1.0" encoding="UTF-8"?>
      <orders xmlns="http://www.bla.com/xml/impex/order/2006-10-31">
<order order-no="00070853">
    <order-date>2015-12-10T21:58:26.000Z</order-date>
    <created-by>storefront</created-by>        
    <taxation>net</taxation>
    <invoice-no>55023028</invoice-no>
    <customer>
        <customer-no>10028489</customer-no>            
    </customer>
    <status>
        <order-status>NEW</order-status>
        <shipping-status>NOT_SHIPPED</shipping-status>
        <confirmation-status>CONFIRMED</confirmation-status>
        <payment-status>NOT_PAID</payment-status>
    </status>        
</order>
<order order-no="10020785">
    <order-date>2015-12-10T21:58:04.000Z</order-date>
    <created-by>storefront</created-by>
    <taxation>net</taxation>
    <invoice-no>12022832</invoice-no>
    <customer>
        <customer-no>10027992</customer-no>
    </customer>
    <status>
        <order-status>NEW</order-status>
        <shipping-status>NOT_SHIPPED</shipping-status>
        <confirmation-status>CONFIRMED</confirmation-status>
        <payment-status>NOT_PAID</payment-status>
    </status>
</order>
     </orders>

Xelement从不同的文件中提取xml并组合回xml

假设您处理的每个文件都有相同的确切结构,您只需读入文件并将元素放入新文档中。您可能需要跟踪从中获取数据的文件。

var orderNo = "00070853";
var dir = @"c:'path'to'files'";
XNamespace ns = "http://www.bla.com/xml/impex/order/2006-10-31";
XNamespace meta = "urn:file.combiner:meta";
var newDoc = new XDocument(
    new XElement(ns + "orders",
        new XAttribute(XNamespace.Xmlns + "meta", meta),
        from p in Directory.EnumerateFiles(dir, @"*.xml")
        from e in XDocument.Load(p).Descendants(ns + "order")
        where (string)e.Attribute("order-no") == orderNo
        select new XElement(e.Name,
            new XAttribute(meta + "path", p), // lets add the original path as an attribute
            e.Nodes()
        )
    )
);