根据用户输入读取XML节点属性

时间:2013-02-05 12:38:19

标签: xml linq c#-4.0 linq-to-xml readxml

<Default>
<SharepointContentType id="SharePointContentType">

<name id="Test1"
         DisplayName="TestOne"
         SharepointGroup="Test1SPGp">
    </name>

<name id="Test2"
         DisplayName="TestTwo"
          SharepointGroup="Test2SPGp">
    </name>
.
.
.
.

</SharepointContentType>
.
.
.
.
<Default>

对于上面的模式,我想下降为,找到一个id为SharePointContentType的节点,而不是查找标签<name >,其中id为Test1(用户定义),而不是获取值元素SharepointGroup

例如,如果用户输入为Test1,则输出应为Test1SPGp请帮助我尝试使用linq并设法编码如下,但无法成功。

    XDocument xDoc = XDocument.Load(GetDefaultXMLFile());

    var feeds = from feed in xDoc.Descendants("name")
                where feed.Attribute("id").Equals("admin")
                select new
                {
                    fxfv = feed.Attribute("SharepointGroup").Value
                };

1 个答案:

答案 0 :(得分:2)

我认为你在哪里有错误,见下文:

feed.Attribute(“id”)返回XAttribute类,因此你不能使用equals来比较字符串,但是在Value属性之后你可以。

        var feeds = from feed in xDoc.Descendants("name")
                    where feed.Attribute("id").Value.Equals("Test1")
                    select new
                    {
                        fxfv = feed.Attribute("SharepointGroup").Value
                    };