从xml文件中获取字符串
我有一个代码试图获取 url 存在的 xml 文件的 id。
我的代码
public static string GetPageIdByUrl(string url)
{
string folder = HttpContext.Current.Server.MapPath("/App_Data/Pages/" + Path.DirectorySeparatorChar);
foreach (string file in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly))
{
var xml = XDocument.Load(file);
var q = from f in xml.Descendants("Page")
where (string)f.Element("Url").Value == url
select (string)f.Attribute("Id").Value;
if (q.Count() != 0)
{
return q.SingleOrDefault();
}
}
return null;
}
出现此错误:
未将对象引用设置为对象的实例。 行:select f.Attribute("Id").Value;
如果 xml 文件中存在“test”
我希望它返回属性 ID。但这 sem 仅适用于第一个 xml 文件。
希望你能解决这个问题。
i have a coode that are trying to get the id of xml file where url exist.
My code
public static string GetPageIdByUrl(string url)
{
string folder = HttpContext.Current.Server.MapPath("/App_Data/Pages/" + Path.DirectorySeparatorChar);
foreach (string file in Directory.GetFiles(folder, "*.xml", SearchOption.TopDirectoryOnly))
{
var xml = XDocument.Load(file);
var q = from f in xml.Descendants("Page")
where (string)f.Element("Url").Value == url
select (string)f.Attribute("Id").Value;
if (q.Count() != 0)
{
return q.SingleOrDefault();
}
}
return null;
}
I get this error:
Object reference not set to an instance of an object.
Line: select f.Attribute("Id").Value;
if "test" exist in a xml file <Url>test</Url>
i want it to return the attribute ID. But that sems only work for the first xml file.
Hope you get the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试发布一些示例 XML。
我猜您的 Url 元素没有“Id”(精确拼写)属性。因此,XNode 为空并且无法提供值。
Try posting some sample XML.
I'm guessing your Url element doesn't have an "Id" (exact spelling) attribute. Therefore the XNode is null and cannot provide a Value.
Id
是Url
元素上的属性吗?然后您需要类似这样的内容:(
请注意,在使用强制转换时,您可以省略
.Value
,因为 XElement 和 XAttribute 定义了对各种基本类型的强制转换。这通常是意外 NullReferenceException 的来源。)Is
Id
an attribute on theUrl
element?Then you need something like this:
(Note that you can leave out
.Value
when using casts as XElement and XAttribute define casts to various base types. This is often a source of unexpected NullReferenceExceptions.)我今天可能很累,问题是在 xml 文件中属性被称为“id”而不是“Id”。
I mabye tirred today,the problem was that in the xml file the attribute was calld "id" and not "Id".
您考虑过使用 XPath 来代替吗?
我已经有一段时间没有使用该语法了,但是查询应该类似于以下内容:
使用 SelectNodes(),您应该获得适合您的查询的节点列表,并且您可以从这些节点获得属性值。
Have you considered using XPath instead?
It's been a while since I've used the syntax, but the query should look something similar to this:
Using SelectNodes(), you should get a list of nodes that fit to your query, and from whom you could get the attribute's value.