需要有关 LINQ to XML 的帮助
总之,我是 Linq to XML 的新手,并且有一个关于如何根据供应商规定的以下格式从包含嵌套目录名称的 List
生成 XML 的问题。 - 请帮忙。谢谢
供应商格式:
<eccu>
<match:recursive-dirs value="store" >
<match:recursive-dirs value="images" >
<revalidate>now</revalidate>
</match:recursive-dirs>
</match:recursive-dirs>
</eccu>
这是我的代码。然而,正如您所看到的,它不会产生格式正确的结果。:
// NOTE - textBox1.Text = 'http://www.someurl.com/dir1/di2/images'
var dirs = (new Uri(textBox1.Text)).Segments.Select(dir => dir.Replace("/", String.Empty)).Where( dir => !String.IsNullOrWhiteSpace(dir)).ToList();
var x = new XDocument(new XDeclaration("1.0", null, null), new XElement("eccu", from s in dirs select new XElement("recursive-dirs", new XAttribute("value", s)), new XElement("revalidate", "now")));
这会产生:
<eccu>
<recursive-dirs value="dir1" />
<recursive-dirs value="dir2" />
<recursive-dirs value="images" />
<revalidate>now</revalidate>
</eccu>
All, I'm new to Linq to XML and have a question on how to generate XML, based on the following format prescribed by a vendor, from a List<string>
containing the names of nested directories. - Please help. Thanks
Vendor format:
<eccu>
<match:recursive-dirs value="store" >
<match:recursive-dirs value="images" >
<revalidate>now</revalidate>
</match:recursive-dirs>
</match:recursive-dirs>
</eccu>
Here's my code. However as you can see it does not produce the correctly formatted results.:
// NOTE - textBox1.Text = 'http://www.someurl.com/dir1/di2/images'
var dirs = (new Uri(textBox1.Text)).Segments.Select(dir => dir.Replace("/", String.Empty)).Where( dir => !String.IsNullOrWhiteSpace(dir)).ToList();
var x = new XDocument(new XDeclaration("1.0", null, null), new XElement("eccu", from s in dirs select new XElement("recursive-dirs", new XAttribute("value", s)), new XElement("revalidate", "now")));
This produces:
<eccu>
<recursive-dirs value="dir1" />
<recursive-dirs value="dir2" />
<recursive-dirs value="images" />
<revalidate>now</revalidate>
</eccu>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 XML 稍微不正确,因为它需要定义命名空间“匹配”。
以下代码将生成具有正确定义的命名空间属性的 XML
(
取自 http://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.xmlns.aspx)
您需要相应地调整您的代码。
Your XML is slightly incorrect as it needs to define the namespace "match".
The following code will produce XML with the namespace attribute correctly defined
which produces
(taken from http://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.xmlns.aspx)
You'll need to adjust your code accordingly.
类似这样的事情应该以硬编码的方式完成,假设
match:recursive-dirs
是有效的 xml(我不知道)。由于您讨论的是列表字符串,因此我需要查看它们的格式才能编写 LINQ 语句。基于 HookedOnLink.com
根据评论进行编辑
它不那么漂亮,但
产生
Something like this should do it in a hard coded fashion, assuming
match:recursive-dirs
is valid xml (I don't know). Since you are talking about a list strings, I will need to see their format to work up a LINQ statement.based on HookedOnLink.com
Edit based on comments
It's not as pretty, but
produces