如何将外部 XML 包含到 XML 文件中 - 两个文件应该是什么样子

发布于 2024-12-05 04:56:50 字数 823 浏览 0 评论 0原文

我正在使用 .NET C# XML 和 LINQ 来更新/删除/插入我的 XML 文件。

我有一个如下所示的 XML 文件 (image1),我只想包含第二个 XML文件。

第一个 XML 文件是原始文件,我不想碰这个文件。所以我更喜欢参考第二个。文件(外部文件),这样我就可以在其中添加/删除 XML 行,而不是 Mainf XML 文件。

但是如何将第二个 XML(外部文件)包含或合并到第一个 XML 中呢? 我只需要在红色框中看到标签(参见红色框)。

<RewriterRule>
   <LookFor>        </LookFor>
   <SendTo>         </SendTo>
</RewriterRule>

问题:

1- 我需要为 XML 文件 1 中的代码编写什么,以便包含 XML 文件 2(外部文件)中的代码?

2- 我的 XMLfile 2(外部文件)应该是什么样子?事实上,我需要我认为的标签,因为我正在阅读 XML XDocument xdoc = XDocument.Load(this.Server.MapPath(path)); 并进行一些更新/删除...... .

原始文件

IMAG2 - 外部文件 在此处输入图像描述

I'm using .NET C# XML and LINQ to Update/delete/insert my XML file.

I've got an XML file looks like below (image1) and I would like to inlcude just the 2nd XML file.

The first XML file is the original file and I don't want to touch this file. So I prefer a reference to a 2nd. file (external file) so I can add/remove XML lines there in stead of the Mainf XML file.

But how can do include or merge the 2nd XML (External file) in to the FIRST?
I just need to the tags (see RED box) from see in RED box.

<RewriterRule>
   <LookFor>        </LookFor>
   <SendTo>         </SendTo>
</RewriterRule>

Question:

1- What do I need to write for code in XML file 1 so my code in XMLfile 2 (external file) is included?

2- How should my XMLfile 2 (external file) look like? In fact I need the tags I think, because I'm reading the XML XDocument xdoc = XDocument.Load(this.Server.MapPath(path));and doing some update/deletes.....

Original file

IMAG2 - EXTERNAL FILE
enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清音悠歌 2024-12-12 04:56:50

从第二个文件添加元素很容易:

XDocument doc1 = XDocument.Load(MapPath("file1.xml"));
doc1.Root.Element("Rules").Add(XDocument.Load(MapPath("file2.xml")).Root.Element("Rules").Elements("RewriterRule"));

// now save to third file with e.g.
doc1.Save(MapPath("updated.xml"));
// or overwrite first file e.g.
doc1.Save(MapPath("file1.xml"));

另一方面,术语“合并”表明您可能想要做一些更复杂的事情,例如根据某些 id 或键识别元素,然后不只是添加新元素,而是覆盖一些数据。如果您在编写代码时需要帮助,您将需要提供有关您想要哪种合并过程的更多详细信息。

[编辑] 下面是一个关于如何使用基于 DTD 的外部实体引用机制将 XML 片段文件包含到另一个文档中的示例: file1.xml 如下:

<!DOCTYPE example [
  <!ENTITY e1 SYSTEM "fragment.xml">
]>
<example>
  <data>
    <item>1</item>
    &e1;
  </data>
</example>

fragment.xml 如下:

<?xml version="1.0" encoding="utf-8" ?>
<item>2</item>

然后,在读取时在使用 LINQ to XML 和 .NET 4.0 的主文件中,您需要确保您使用的 XmlReader 设置为解析 DTD,例如

        XDocument doc;
        using (XmlReader xr = XmlReader.Create("file1.xml", new XmlReaderSettings() { DtdProcessing = System.Xml.DtdProcessing.Parse }))
        {
            doc = XDocument.Load(xr);
        }

Well adding elements from a second file is easy:

XDocument doc1 = XDocument.Load(MapPath("file1.xml"));
doc1.Root.Element("Rules").Add(XDocument.Load(MapPath("file2.xml")).Root.Element("Rules").Elements("RewriterRule"));

// now save to third file with e.g.
doc1.Save(MapPath("updated.xml"));
// or overwrite first file e.g.
doc1.Save(MapPath("file1.xml"));

On the other hand the term "merging" suggests you might want to do something more complex like identifying elements based on some id or key and then not simply add new elements but overwrite some data. You will need to provide more details on exactly what kind of merge process you want if you need help with writing the code.

[edit] Here is an example on how to use the DTD based mechanism of a reference to an external entity to include an XML fragment file into another document: file1.xml is as follows:

<!DOCTYPE example [
  <!ENTITY e1 SYSTEM "fragment.xml">
]>
<example>
  <data>
    <item>1</item>
    &e1;
  </data>
</example>

fragment.xml is as follows:

<?xml version="1.0" encoding="utf-8" ?>
<item>2</item>

Then, when reading in the main file with LINQ to XML and .NET 4.0 you need to make sure the XmlReader you use is set to parse the DTD e.g.

        XDocument doc;
        using (XmlReader xr = XmlReader.Create("file1.xml", new XmlReaderSettings() { DtdProcessing = System.Xml.DtdProcessing.Parse }))
        {
            doc = XDocument.Load(xr);
        }
坐在坟头思考人生 2024-12-12 04:56:50

XInclude W3C 标签有一种更好的方法。这是我的 Linq to XML 扩展方法:

/// <summary>
/// Linq to XML XInclude extentions
/// </summary>
public static class XIncludeExtention
{
    #region fields

    /// <summary>
    /// W3C XInclude standard
    /// Be aware of the different 2001 and 2003 standard.
    /// </summary>
    public static readonly XNamespace IncludeNamespace = "http://www.w3.org/2003/XInclude";

    /// <summary>
    /// Include element name
    /// </summary>
    public static readonly XName IncludeElementName = IncludeNamespace + "include";

    /// <summary>
    /// Include location attribute
    /// </summary>
    public const string IncludeLocationAttributeName = "href";

    /// <summary>
    /// Defines the maximum sub include count of 25
    /// </summary>
    public const int MaxSubIncludeCountDefault = 25;

    #endregion


    #region methods


    /// <summary>
    /// Replaces XInclude references with the target content.
    /// W3C Standard: http://www.w3.org/2003/XInclude
    /// </summary>
    /// <param name="xDoc">The xml doc.</param>
    /// <param name="maxSubIncludeCount">The max. allowed nested xml includes (default: 25).</param>
    public static void ReplaceXIncludes(this XDocument xDoc, int maxSubIncludeCount = MaxSubIncludeCountDefault)
    {
        ReplaceXIncludes(xDoc.Root, maxSubIncludeCount);
    }

    /// <summary>
    /// Replaces XInclude references with the target content.
    /// W3C Standard: http://www.w3.org/2003/XInclude
    /// </summary>
    /// <param name="xmlElement">The XML element.</param>
    /// <param name="maxSubIncludeCount">The max. allowed nested xml includes (default: 25).</param>
    public static void ReplaceXIncludes(this XElement xmlElement, int maxSubIncludeCount = MaxSubIncludeCountDefault)
    {
        xmlElement.ReplaceXIncludes(1, maxSubIncludeCount);
    }

    private static void ReplaceXIncludes(this XElement xmlElement, int subIncludeCount, int maxSubIncludeCount)
    {
        var results = xmlElement.DescendantsAndSelf(IncludeElementName).ToArray<XElement>();    // must be materialized

        foreach (var includeElement in results)
        {
            var path = includeElement.Attribute(IncludeLocationAttributeName).Value;
            path = Path.GetFullPath(path);

            var doc = XDocument.Load(path);
            if (subIncludeCount <= maxSubIncludeCount)  // protect mutal endless references
            {
                // replace nested includes
                doc.Root.ReplaceXIncludes(++subIncludeCount, maxSubIncludeCount);
            }
            includeElement.ReplaceWith(doc.Root);
        }
    }

    #endregion
}

该代码的灵感来自以下博客文章:
http://catarsa.com/Articles/Blog /Any/Any/Linq-To-Xml-XInclude?MP=pv

更多 XInclude 信息:
http://msdn.microsoft.com/en-us/library/aa302291.aspx

There is a better approach with the XInclude W3C Tag. Here is my Linq to XML extention method:

/// <summary>
/// Linq to XML XInclude extentions
/// </summary>
public static class XIncludeExtention
{
    #region fields

    /// <summary>
    /// W3C XInclude standard
    /// Be aware of the different 2001 and 2003 standard.
    /// </summary>
    public static readonly XNamespace IncludeNamespace = "http://www.w3.org/2003/XInclude";

    /// <summary>
    /// Include element name
    /// </summary>
    public static readonly XName IncludeElementName = IncludeNamespace + "include";

    /// <summary>
    /// Include location attribute
    /// </summary>
    public const string IncludeLocationAttributeName = "href";

    /// <summary>
    /// Defines the maximum sub include count of 25
    /// </summary>
    public const int MaxSubIncludeCountDefault = 25;

    #endregion


    #region methods


    /// <summary>
    /// Replaces XInclude references with the target content.
    /// W3C Standard: http://www.w3.org/2003/XInclude
    /// </summary>
    /// <param name="xDoc">The xml doc.</param>
    /// <param name="maxSubIncludeCount">The max. allowed nested xml includes (default: 25).</param>
    public static void ReplaceXIncludes(this XDocument xDoc, int maxSubIncludeCount = MaxSubIncludeCountDefault)
    {
        ReplaceXIncludes(xDoc.Root, maxSubIncludeCount);
    }

    /// <summary>
    /// Replaces XInclude references with the target content.
    /// W3C Standard: http://www.w3.org/2003/XInclude
    /// </summary>
    /// <param name="xmlElement">The XML element.</param>
    /// <param name="maxSubIncludeCount">The max. allowed nested xml includes (default: 25).</param>
    public static void ReplaceXIncludes(this XElement xmlElement, int maxSubIncludeCount = MaxSubIncludeCountDefault)
    {
        xmlElement.ReplaceXIncludes(1, maxSubIncludeCount);
    }

    private static void ReplaceXIncludes(this XElement xmlElement, int subIncludeCount, int maxSubIncludeCount)
    {
        var results = xmlElement.DescendantsAndSelf(IncludeElementName).ToArray<XElement>();    // must be materialized

        foreach (var includeElement in results)
        {
            var path = includeElement.Attribute(IncludeLocationAttributeName).Value;
            path = Path.GetFullPath(path);

            var doc = XDocument.Load(path);
            if (subIncludeCount <= maxSubIncludeCount)  // protect mutal endless references
            {
                // replace nested includes
                doc.Root.ReplaceXIncludes(++subIncludeCount, maxSubIncludeCount);
            }
            includeElement.ReplaceWith(doc.Root);
        }
    }

    #endregion
}

The code was inspired by following blog post:
http://catarsa.com/Articles/Blog/Any/Any/Linq-To-Xml-XInclude?MP=pv

Further XInclude infos:
http://msdn.microsoft.com/en-us/library/aa302291.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文