gpt4 book ai didi

c# - 如何在新行中用特定元素替换多个
标签?

转载 作者:数据小太阳 更新时间:2023-10-29 02:09:48 26 4
gpt4 key购买 nike

我有一个包含多个 <p> 的 XML 文件标签在里面。一些 <p>标签包含 <br/>在里面。所以,我应该创建一个新的 XElement对于每个 <br/>在标签中。我试图通过使用 foreach 阅读每一行来实现并替换每个 <br/></p> + Environment.NewLine + <p> .

它有效,但如果<p>包含类似 <b> 的标签或 <i> , 然后 <>成为&lt;&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>

最佳答案

这可能不是最好的答案,但它可以满足您的大部分需求:

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();
}

关于c# - 如何在新行中用特定元素替换多个 <br/> 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55741823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com