【发布时间】:2016-06-08 07:20:35
【问题描述】:
我已经在网上搜索了一下,也找到了解决我的问题的方法,但我相信有可能减少必要的编码量。我希望你能帮助我。
我有以下 XML,我需要通过 id 从标题中获取值。 (在这种情况下,我对标题“somefile2.jpg”感兴趣,我需要通过“2”的 id 找到它)
<entry>
<name></name>
<title type="text">somefile1.jpg</title>
<m:properties xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
<d:path></path>
<d:id>1</d:id>
</m:properties>
</entry>
<entry>
<name></name>
<title type="text">somefile2.jpg</title>
<m:properties xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
<d:path></path>
<d:id>2</d:id>
</m:properties>
</entry>
<entry>
<name></name>
<title type="text">somefile3.jpg</title>
<m:properties xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices">
<d:path></path>
<d:id>3</d:id>
</m:properties>
</entry>
为了解决这个问题,我运行以下代码:
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xmlfile);
XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(xDoc.NameTable);
nameSpaceManager.AddNamespace("b", "http://www.w3.org/2005/Atom");
nameSpaceManager.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
nameSpaceManager.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
//Find the correct XML node by child ID and get it's title
XmlNode parentNode = null;
string incomingID = "2";
foreach (XmlNode node in xDoc.SelectNodes(@"//m:properties/d:id", nameSpaceManager))
{
if (node.InnerText == incomingID)
{
parentNode = node.ParentNode.ParentNode;
break;
}
}
//Add the nodes to a new XML document so it can be traversed
XmlDocument parent = new XmlDocument();
parent.LoadXml("<root>" + parentNode.InnerXml + "</root>");
XmlNamespaceManager parentNameSpaceManager = new XmlNamespaceManager(parent.NameTable);
parentNameSpaceManager.AddNamespace("b", "http://www.w3.org/2005/Atom");
parentNameSpaceManager.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
parentNameSpaceManager.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
string xmlFilename = parent.GetElementsByTagName("title")[0].InnerText;
如果可能的话,我想更改代码,这样我就不会为了查找标题而创建一个全新的 XmlDocument。您认为可以通过一些较短的代码来获得标题吗?我在想一些事情:
string xmlFilename = xDoc.SelectSingleNode(@"//m:properties[id='" + incomingID + "']", nameSpaceManager).ParentNode.ParentNode.FirstChild["title"].InnerText;
如果我运行上面的代码,它会返回一个异常:Objectreference not set to an instance of an object
【问题讨论】:
-
好吧,我当然可以做到这一点,但我希望有一些更动态的东西,所以我不直接控制要获取树中的哪个节点:string xmlFilename = parentNode.FirstChild.NextSibling .InnerText;