从数据库中获取 XML 并合并它们

Fetch XML from database & merge them

我有一个 table,其中具有 xml 数据类型的列有许多 xml 格式如下。

 <Hash HashValue = "9738839398923">
     <Element1>
            <childelement1 attribute1 = "..." attribute2 = "...">
            <childelement2 attribute1 = "..." attribute2 = "...">
            <childelement3 attribute1 = "..." attribute2 = "...">
    </Element1>
    <Element2>
           ......
           ......
    </Element2>
</Hash>

现在,我想从 table 中获取所有这些行并合并它们。我已经完成了获取部分并将其存储在 Datatable.

为了合并,我在这个网站上尝试了不同的解决方案,但我得不到满意的结果。

预期输出格式:

    <Hash HashValue = "4972904980">
         .......
         ......
     </Hash>
    <Hash HashValue = "4534543">
         .......
         ......
     </Hash>
   <Hash HashValue = "536456456456">
         .......
         ......
     </Hash>

到目前为止我得到的最接近的是:

<Hash HashValue = "4972904980">
      <Hash HashValue = "4534543">
         .......
         ......
     </Hash>
  </Hash>

以上输出代码:

            FileStream file = File.Open(fakePath, FileMode.Create);
            XElement xFileRoot = XElement.Parse(dt.Rows[0]["ColumnName"].ToString());
            XElement xFileChild = XElement.Parse(dt.Rows[1]["ColumnName"].ToString());
            xFileRoot.Add(xFileChild);
            xFileRoot.Save(file); 

上面的代码显然将第二个 xml 视为第一个的 child 这显然不是我的意图。

如何实现我的预期输出?

要使 XML 有效,必须有 1 个单根元素。

您正在添加下一个 "element" 作为根的子项。如果根元素和子元素是同一个元素,这就没有意义了。

我建议你简单地做一个虚拟的根元素叫做?根元素?

XmlElement xFileRoot = doc.CreateElement("rootElement");

然后

foreach(var row in dt.Rows)
{
   XElement xFileChild = XElement.Parse(row["ColumnName"].ToString());
   xFileRoot.Add(xFileChild);
}

并且为了所有意图忽略根元素的存在。

换句话说,您想要的结果无效 XML。

XML 只允许一个根元素。所以您需要明确地创建该元素 - 它不能是您现有的元素之一。

一种方法:

        XDocument xDocument = new XDocument();
        var root = new XElement("root");
        xDocument.Add(root);

        root.Add(XElement.Parse("<entry hash='1'/>"));
        root.Add(XElement.Parse("<entry hash='2'/>"));

        var output = string.Join("\r\n", root.Elements());

您应该遍历记录,而不是两个 root.Add 语句。

这不是创建 XML 的最有效方法 - 但是将数据读入 DataTable 也不是 - 所以如果它对你来说足够快,那就没问题。