【问题标题】:How do I create a new XElement for each </br> tag in XML in c#?如何在 c# 中为 XML 中的每个 </br> 标签创建一个新的 XElement?
【发布时间】:2019-09-07 07:37:04
【问题描述】:

我的 XML 包含如下数据:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE repub SYSTEM "C:\repub\Repub_V1.dtd">
<?xml-stylesheet href="C:\repub\repub.xsl" type="text/xsl"?>
<repub>
<head>
<title>xxx</title>
</head>
<body>
<sec>
<title>First Title</title>
<break name="1-1"/>
<h1><page num="1"/>First Heading</h1>
<bl>This is another text</bl>
<fig><img src="images/img_1-1.jpg" alt=""/><fc>This is a caption</fc></fig>
<p>This<br/> again is<br/> a paragraph</p>
</sec>
</body>
</repub>

它包含一个&lt;p&gt; 标签和多个&lt;br/&gt; 标签。我想为每个&lt;br/&gt; 创建一个新的&lt;p&gt;

我想要达到的目标:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE repub SYSTEM "C:\repub\Repub_V1.dtd">
<?xml-stylesheet href="C:\repub\repub.xsl" type="text/xsl"?>
<repub>
<head>
<title>xxx</title>
</head>
<body>
<sec>
<title>First Title</title>
<break name="1-1"/>
<h1><page num="1"/>First Heading</h1>
<bl>This is another text</bl>
<fig><img src="images/img_1-1.jpg" alt=""/><fc>This is a caption</fc></fig>
<p>This</p>
<p>again is</p>
<p>a paragraph</p>
</sec>
</body>
</repub>

我不知道如何继续。

我尝试过的:

我正在尝试使用以下方法来解决它:

foreach (var item in xdoc.Descendants("p"))
{
    if (item.Elements("br").Count() > 0)
    {
        foreach (var br in item.Elements("br"))
        {
            //Do something
        }
    }
}

【问题讨论】:

    标签: c# .net xml foreach


    【解决方案1】:

    使用 Xml Linq:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    using System.IO;
    
    
    namespace ConsoleApplication108
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
    
                List<XElement> brs = doc.Descendants("br").ToList();
    
                for (int i = brs.Count - 1; i >= 0; i--)
                {
                    brs[i].ReplaceWith(new XElement("br", new XElement("p", new object[] {brs[i].Attributes(), brs[i].Nodes()})));
                }
    
    
            }
    
        }
    
    
    }
    

    【讨论】:

    • 这只是将&lt;br/&gt; 标签替换为&lt;p/&gt; 标签。我想要的是问题,但这并没有实现。
    • 我修改了一行。示例输出与请求中的文字不一致。
    • &lt;p&gt;This is a value that needs &lt;br&gt;&lt;p /&gt;&lt;/br&gt;to be separated by break&lt;br&gt;&lt;p /&gt;&lt;/br&gt;tags into separate paragraph &lt;br&gt;&lt;p /&gt;&lt;/br&gt;tags in multiple lines.&lt;/p&gt;。这就是我得到的。
    猜你喜欢
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多