首页 > 解决方案 > 如何
用新行中的特定元素替换多个标签?

问题描述

我有一个 XML 文件,其中包含多个<p>标签。其中包含一些<p>标签<br/>。所以,我应该为标签中XElement的每个创建一个新的。<br/>我试图通过使用读取每一行foreach并将每一行替换<br/></p> + Environment.NewLine + <p>.

它可以工作,但如果<p>包含类似<b>or <i>、 then<>become &lt;and之类的标签&gt;。这就是为什么我想要一种linq方法或一种foreach方法,以便能够在 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"/>
<pps>This is Sparta</pps>
<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 is a sentence<br/> that will be broken down <br/>into separate paragraph tags.</p>
</break>
</sec>
</body>
</repub>

我想要的是:

<?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"/>
<pps>This is Sparta</pps>
<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 is a sentence</p>
<p>that will be broken down</p>
<p>into separate paragraph tags.</p>
</break>
</sec>
</body>
</repub>

我尝试了什么:

List<XElement> brs = xdoc.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()})));
}

在我的一个较早的问题中,我从 StackOverflow itslef 获得了这段代码。

我得到什么:

<?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"/>
<pps>This is Sparta</pps>
<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 is a sentence<br><p/></br> that will be broken down <br><p/></br>into separate paragraph tags.</p>
</break>
</sec>
</body>
</repub>

标签: c#.netxmllinq

解决方案


这可能不是最好的答案,但它会做你想做的大部分事情:

List<XElement> p = xdoc.Descendants("p").ToList();
for (int i = p.Count - 1; i >= 0; i--)
{
    var newP = new XElement("p");
    newP.ReplaceAttributes(p[i].Attributes());

    foreach (var node in p.Nodes())
    {
        if (node.NodeType == System.Xml.XmlNodeType.Element && ((XElement)node).Name == "br")
        {
            p[i].AddBeforeSelf(newP);
            newP = new XElement("p");
            newP.ReplaceAttributes(p[i].Attributes());
        }
        else
        {
            newP.Add(node);
        }
    }
    p[i].AddBeforeSelf(newP);
    p[i].Remove();
}

推荐阅读