如何通过另一个子节点从父节点获取childnode innertext

时间:2016-06-08 07:20:35

标签: xml nodes parent children

我已经在网上搜索了一下,并找到了我的问题的解决方案,但我相信可以减少必要的编码量。我希望你能帮助我。

我有以下XML,我需要通过id从title获取值。 (在这种情况下,我感兴趣的是标题" somefile2.jpg"我需要通过" 2"来找到它。)

<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;

如果我运行上面的代码,它会返回一个Exception:Objectreference未设置为对象的实例

1 个答案:

答案 0 :(得分:1)

Omg ..像往常一样,当你发布了一个问题后,你不久就会找到答案。这是我的解决方案:

string xmlFilename = parentNode["title"].InnerText;

这意味着我终于可以删除可怕的第二个XmlDocument。 :)

相关问题