웹 검색에 약간의 문제가 있지만 내 문제에 대한 해결책을 찾았지만 필요 한 코딩의 양을 줄일 수 있다고 생각합니다. 네가 나를 도울 수 있기를 바랐다.어떻게 다른 childnode에 의해 부모로부터 childnode innertext를 얻을 수 있습니까?
다음 XML을 가지고 있으며 ID로 제목에서 값을 가져와야합니다.
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;
:
<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>
내가 다음 코드를 실행이 문제를 해결하기 위해 (이 경우 내가 "2"의 ID로 찾을 필요가 제목 "somefile2.jpg"에 관심이)
가능한 경우 제목을 찾기 위해 완전히 새로운 XmlDocument를 만들지 않도록 코드를 변경하고 싶습니다. 좀 더 짧은 코드로 제목을 얻는 것이 가능하다고 생각하십니까? 내가 위의 코드를 실행하면
string xmlFilename = xDoc.SelectSingleNode(@"//m:properties[id='" + incomingID + "']", nameSpaceManager).ParentNode.ParentNode.FirstChild["title"].InnerText;
그것은 예외를 반환 : 당신이 게시 한 때 평소와 같이 ObjectReference의 객체
물론이 작업을 수행 할 수 있지만 좀 더 동적 인 뭔가를 기대하고 있었으므로 트리에서 어느 노드를 가져 오는 지 직접 제어하지는 못합니다. string xmlFilename = parentNode.FirstChild.NextSibling.InnerText; – Ghost