我有一个包含多个<p>标签的 XML 文件。一些<p>标签包含<br/>在其中。所以,我应该为标签中的XElement每个创建一个新<br/>的。我试图通过使用读取每一行foreach并将每一行替换<br/>为</p> + Environment.NewLine + <p>.
它的工作原理,但如果<p>包含这样的标签<b>或<i>,然后<和>成为<和>分别。这就是为什么我想要一种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>
Run Code Online (Sandbox Code Playgroud)
我想要的是:
<?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>
Run Code Online (Sandbox Code Playgroud)
我试过的:
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()})));
}
Run Code Online (Sandbox Code Playgroud)
我在一个较旧的问题中从 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>
Run Code Online (Sandbox Code Playgroud)
这可能不是最好的答案,但它可以满足您的大部分需求:
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();
}
Run Code Online (Sandbox Code Playgroud)