简体   繁体   English

将一个XML文档转换为另一个XML文档

[英]Converting one XML document into another XML document

I want to convert an XML document containing many elements within a node (around 150) into another XML document with a slightly different schema but mostly with the same element names. 我想将包含节点内的许多元素(大约150个)的XML文档转换为另一个XML文档,该文档具有略微不同的模式,但大多数具有相同的元素名称。 Now do I have to manually map each element/node between the 2 documents. 现在我必须手动映射2个文档之间的每个元素/节点。 For that I will have to hardcode 150 lines of mapping and element names. 为此,我将不得不硬编码150行映射和元素名称。 Something like this: 像这样的东西:

XElement newOrder = new XElement("Order");
newOrder.Add(new XElement("OrderId", (string)oldOrder.Element("OrderId")),
newOrder.Add(new XElement("OrderName", (string)oldOrder.Element("OrderName")),
...............
...............
...............and so on

The newOrder document may contain additional nodes which will be set to null if nothing is found for them in the oldOrder. newOrder文档可能包含其他节点,如果在oldOrder中找不到任何节点,则这些节点将设置为null。 So do I have any other choice than to hardcode 150 element names like orderId, orderName and so on... Or is there some better more maintainable way? 那么除了硬编码150个元素名称(如orderId,orderName等)之外,我还有其他选择......还是有一些更好的可维护方式?

Use an XSLT transform instead. 请改用XSLT转换 You can use the built-in .NET XslCompiledTransform to do the transformation. 您可以使用内置的.NET XslCompiledTransform进行转换。 Saves you from having to type out stacks of code. 使您免于输入堆栈代码。 If you don't already know XSL/XSLT, then learning it is something that'll bank you CV :) 如果你还不知道XSL / XSLT,那么学习它就会让你自己知道:)

Good luck! 祝好运!

使用XSLT转换将旧的xml文档转换为新格式。

XElement.Add has an overload that takes object[]. XElement.Add有一个带对象[]的重载

List<string> elementNames = GetElementNames();

newOrder.Add(
  elementNames
    .Select(name => GetElement(name, oldOrder))
    .Where(element => element != null)
    .ToArray()
  );

// //

public XElement GetElement(string name, XElement source)
{
  XElement result = null;
  XElement original = source.Elements(name).FirstOrDefault();
  if (original != null)
  {
    result = new XElement(name, (string)original)
  }
  return result;
}

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

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