【发布时间】:2018-09-22 14:41:13
【问题描述】:
我有一个要写入文件的 XDocument(在下面的“//XDocument”注释下列出)但是一旦我使用我的写入方法,它在下面的“//writing method”注释下写,我得到了一个像“</>”这样的不完整结尾而不是像“</script>"”这样的完整结尾。我需要以某种方式解决这个问题。
我的代码:
private static void Execute()
{
string outputXMLFile = outputXMLFile = @"C:\Temp\testPoints6.html";
//XDocument
XDocument documentElement =
new XDocument(
new XDeclaration(
"1.0",
Encoding.Default.ToString(), null
)
,
new XDocumentType(
"html", null, null, null
));
XElement html = new XElement("html");
XElement head = new XElement("head");
html.Add(new XAttribute("lang", "ru"));
head.Add(
new XElement("title",
"Exported X3DOM Scene"));
head.Add(
new XElement("meta",
new XAttribute("http-equiv", "X-UA-Compatible"),
new XAttribute("content", "chrome=1")));
head.Add(
new XElement("meta",
new XAttribute("http-equiv", "Content-Type"),
new XAttribute("content", "text/html;charset=utf-8")));
head.Add(
new XElement("link",
new XAttribute("rel", "stylesheet"),
new XAttribute("type", "text/css"),
new XAttribute("href", "http://www.x3dom.org/x3dom/release/x3dom.css")));
head.Add(
new XElement("script",
new XAttribute("type", "text/javascript"),
new XAttribute("src", "http://www.x3dom.org/x3dom/release/x3dom.js")
));
html.Add(head);
documentElement.Add(html);
//writing method
XmlWriterSettings xws = new XmlWriterSettings();
xws.Encoding = Encoding.Default;
xws.Indent = true;
xws.NewLineOnAttributes = true;
using ( XmlWriter xw = XmlWriter.Create(outputXMLFile, xws) ) {
documentElement.WriteTo(xw);
xw.Flush();
}
}
输出:
<?xml version="1.0" encoding="windows-1251"?>
<!DOCTYPE html >
<html
lang="ru">
<head>
<title>Exported X3DOM Scene</title>
<meta
http-equiv="X-UA-Compatible"
content="chrome=1" />
<meta
http-equiv="Content-Type"
content="text/html;charset=utf-8" />
<link
rel="stylesheet"
type="text/css"
href="http://www.x3dom.org/x3dom/release/x3dom.css" />
<script
type="text/javascript"
src="http://www.x3dom.org/x3dom/release/x3dom.js" />
</head>
</html>
所以我需要这个 XmlWriter 将“<script> </script>”写入我的文件而不是“<script .../>”,这是不正确的,当我在浏览器中运行它时会引起一些麻烦
我采用“解决方案”来包含这篇文章的结束标签:“How do you force explicit tag closing with Linq XML?”,但它似乎不起作用
【问题讨论】:
-
“我采用了“解决方案”来包含结束标记...” - 显然,您没有。至少不在您发布的代码中。该解决方案的想法是添加元素(例如
"script")并将值显式设置为string.Empty(或"")。 -- 所以试试var scriptElement = new XElement("script", string.Empty); head.Add(scriptElement);,然后将属性添加到scriptElement。 -
Corak,哦,是的,谢谢 xD 它有效。在我意识到之前,我只是拿了一个代码示例,并没有尝试其他代码示例和其他解决方案
标签: c# xml visual-studio-2015 linq-to-xml