名称空间相同名称的节点 - 所需属性的内容

时间:2013-11-02 22:44:22

标签: c# xml

得到了这份文件:

<uniprot xmlns="http://uniprot.org/uniprot" xmlns:xsi="http://www.w3.org/2001/    XMLSchema-instance" xsi:schemaLocation="http://uniprot.org/uniprot http://www.uniprot.org/support/docs/uniprot.xsd">
<entry dataset="Swiss-Prot" created="1986-07-21" modified="2013-10-16" version="88">
<dbReference type="GO" id="GO:0006412">
<property type="term" value="P:translation"/>
<property type="evidence" value="IEA:InterPro"/>
</dbReference>
<dbReference type="HAMAP" id="MF_00294">
<property type="entry name" value="Ribosomal_L33"/>
<property type="match status" value="1"/>
</dbReference>
<dbReference type="InterPro" id="IPR001705">
<property type="entry name" value="Ribosomal_L33"/>
</dbReference>

现在,我正在使用它来获取节点的内部文本,这很好用......但是......

XmlDocument XMLdoc = new XmlDocument();
XMLdoc.Load(Datapath);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(XMLdoc.NameTable); 
nsmgr.AddNamespace("ns", "http://uniprot.org/uniprot");
String NodeName = XMLdoc.SelectSingleNode("//ns:fullName", nsmgr).InnerText;

...我需要获取属性以及类型的内容是否为GO,如果是,请获取该确切节点的以下数据,即id和value。几个小时以来一直在思考和谷歌搜索,我只是缺乏知识,无处可去。

2 个答案:

答案 0 :(得分:0)

我建议使用Linq to Xml,我发现它比XmlDocument和XPath查询容易得多,但这至少部分是个人偏好。

我不太清楚你用“GO”类型的每个元素的“值”是什么意思,但这应该可以让你在那里大部分时间。 goTypeNodes将包含那些具有“GO”类型及其ID和类型值的节点的集合,并且还包含其下面的属性元素,因此如果“value”表示属性元素的值在他们之下,从那里得到它是微不足道的。

XNamespace ns = "http://uniprot.org/uniprot";
XDocument doc = XDocument.Load(@"C:\SO\Foo.xml");

var goTypeNodes = from n in doc.Descendants(ns + "dbReference")
                    select new { Id = n.Attribute("id").Value, Type = n.Attribute("type").Value, Properties = n.Elements()};

顺便说一句,您的示例XML缺少uniprot和entry的结束标记。

答案 1 :(得分:0)

实际上我设法解决了这个问题:

            XmlNodeList Testi = XMLdoc.SelectNodes("//ns:dbReference", nsmgr);
            foreach (XmlNode xn in Testi)
            {
                if (xn.Attributes["type"].Value == "GO") 
                {
                    String Testilator = xn.Attributes["id"].Value;
                    String Testilator2 = xn.FirstChild.Attributes["value"].Value;

                }
            }