问题:XElement.DescendantNodes()
似乎输出了一些部分TWICE。
背景:
我需要将<body>
元素的全部内容复制到具有嵌入样式的<div>
内的新html文档。这适用于html邮件,其中嵌入式样式应该比样式块更好用,因为许多邮件代理会剥离<head>
部分。但是,我遇到了两个部分的问题。如何解决这个问题?
以下是示例输入:
<body>
some text
<a href="http://www.nix.com/index.html">Click Me</a>
<br />
<span>more text</span>
</body>
这是带有重复字符串的输出,否则它正是我需要的:
<body>
<div style="font-family: Verdana; font-size: 12px;">
some text
<a href="http://www.nix.com/index.html">Click Me</a>
Click Me <<<===duplicate!!!
<br />
<span>more text</span>
more text <<<===duplicate!!!
</div>
</body>
这是代码,我希望DescendantNodes()
应该是提取像<a>
这样的xelement节点和像“some text”这样的文本节点的正确方法:
using System.Xml.Linq;//XElement
XElement InputMail =
new XElement("body",
"some text",
new XElement("a",
new XAttribute("href", "http://www.nix.com/index.html"),
"Click Me"),
new XElement("br"),
new XElement("span", "more text"));
XElement OutputMail =
new XElement("body",
new XElement("div",
new XAttribute("style", "font-family: Verdana; font-size: 12px;"),
InputMail.DescendantNodes()));
答案 0 :(得分:1)
DescendantNodes
将返回所有节点,包括子节点,孙子节点等。这就是为什么你看到重复 - 最内层的节点作为他们各自父母的一部分返回,加上他们自己。您只需要直接子节点,为此您可以使用:
XElement OutputMail =
new XElement("body",
new XElement("div",
new XAttribute("style", "font-family: Verdana; font-size: 12px;"),
InputMail.Nodes()));
答案 1 :(得分:1)
在VB中,我会像这样做
outp.<div>.FirstOrDefault.Add(inp.Nodes)
使用这些声明
Dim inp As XElement = <body>
some text
<a href="http://www.nix.com/index.html">Click Me</a>
<br/>
<span>more text</span>
</body>
Dim outp As XElement = <body>
<div style="font-family: Verdana; font-size: 12px;">
</div>
</body>