简体   繁体   English

从xml文件中获取一个字符串

[英]Get a string from xml files

i have a coode that are trying to get the id of xml file where url exist. 我有一个正在尝试获取url存在的xml文件的id的coode。

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; 行:选择f.Attribute(“Id”)。值;

if "test" exist in a xml file <Url>test</Url> i want it to return the attribute ID. 如果xml文件中存在“test” <Url>test</Url>我希望它返回属性ID。 But that sems only work for the first xml file. 但是这个sems只适用于第一个xml文件。

Hope you get the problem. 希望你能解决问题。

Try posting some sample XML. 尝试发布一些示例XML。

I'm guessing your Url element doesn't have an "Id" (exact spelling) attribute. 我猜你的Url元素没有“Id”(精确拼写)属性。 Therefore the XNode is null and cannot provide a Value. 因此,XNode为null,无法提供值。

Is Id an attribute on the Url element? IdUrl元素的属性吗?

<Pages>
    <Page><Url Id="6428">http://www.example.com/</Url></Page>
</Pages>

Then you need something like this: 然后你需要这样的东西:

var q = from f in xml.Descendants("Page")
        where (string)f.Element("Url") == url
        select (string)f.Element("Url").Attribute("Id");

(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.) (注意,当使用强制转换作为XElement并且XAttribute将转换定义为各种基类型时,可以省略.Value 。这通常是意外NullReferenceExceptions的来源。)

我mabye今天打瞌睡,问题是在xml文件中属性是calld“id”而不是“Id”。

Have you considered using XPath instead? 您是否考虑过使用XPath?

It's been a while since I've used the syntax, but the query should look something similar to this: 我已经使用了语法已经有一段时间了,但查询看起来应该类似于:

/Page[Url='THE_STRING'] /页[URL = 'THE_STRING']

Using SelectNodes(), you should get a list of nodes that fit to your query, and from whom you could get the attribute's value. 使用SelectNodes(),您应该获得适合您的查询的节点列表,并从中获取属性的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM