我需要帮助打印一些 xml。这是我的代码(它不工作它甚至不正确格式化完整的 url,它不理解 url 字符串中的“//”)它也不理解“<”。一定有更好的方法来做到这一点??
foreach (string url in theUrls)
{
fullurl=@"http://www.cambit.com/restaurants" +url;
xml = xml + @"<url>" + Environment.NewLine +
@"<loc>" + fullurl + @"</loc>" + Environment.NewLine +
@"<changefreq>weekly</changefreq>" + Environment.NewLine +
@"<priority>0.80</priority>" + Environment.NewLine +
@"</url>" + Environment.NewLine;
}
它返回 400 个彼此紧挨着的附加项。 Environment.NewLine 也不起作用....
http://www.cambit.com/restaurantsBerwyn weekly 0.80
我试过了,它说 loc 对象没有设置为对象的实例
XmlDocument aNewNode = new XmlDocument();
XmlElement urlRoot = aNewNode.CreateElement("url");
//aNewNode.DocumentElement.AppendChild(urlRoot);
XmlElement loc = aNewNode.CreateElement("loc");
XmlText locText = aNewNode.CreateTextNode(fullurl);
aNewNode.DocumentElement.AppendChild(loc);
aNewNode.DocumentElement.LastChild.AppendChild(locText);
XmlElement chgFreq = aNewNode.CreateElement("changefreq");
XmlText chgFreqText = aNewNode.CreateTextNode("weekly");
aNewNode.DocumentElement.AppendChild(chgFreq);
aNewNode.DocumentElement.LastChild.AppendChild(chgFreqText);
XmlElement priority = aNewNode.CreateElement("priority");
XmlText priorityText = aNewNode.CreateTextNode("0.80");
aNewNode.DocumentElement.AppendChild(priority);
aNewNode.DocumentElement.LastChild.AppendChild(priorityText);
哪里做错了??
请您参考如下方法:
最简单的方法之一是使用 XDocument,它有 lots of documentation .这是文档中的示例:
XDocument srcTree = new XDocument(
new XComment("This is a comment"),
new XElement("Root",
new XElement("Child1", "data1"),
new XElement("Child2", "data2"),
new XElement("Child3", "data3"),
new XElement("Child2", "data4"),
new XElement("Info5", "info5"),
new XElement("Info6", "info6"),
new XElement("Info7", "info7"),
new XElement("Info8", "info8")
)
);
XDocument doc = new XDocument(
new XComment("This is a comment"),
new XElement("Root",
from el in srcTree.Element("Root").Elements()
where ((string)el).StartsWith("data")
select el
)
);
Console.WriteLine(doc);
这适用于您的示例的方式类似于:
public XDocument CreateDocument(IEnumerable<string> theUrls)
{
var urlElements = theUrls.Select(u => CreateUrlElement(u));
return new XDocument(new XElement("Urls", urlElements));
}
public XElement CreateUrlElement(string url)
{
return new XElement("Url",
new XElement("loc", fullUrl),
... the rest of your elements ...);
}
