在 xDocument 中查找节点值
find the node value in xDocument
我无法获取值。
如何获取StatusDescription
值?请告诉我。
<WebServiceResponse xmlns="ws.abc.com">
<SubscriptionInfo xmlns="ws.abc.com">
<LicenseStatusCode>0</LicenseStatusCode>
<Amount>0</Amount>
</SubscriptionInfo>
<VerificationResponse xmlns="www.abc.com">
<VerificationResult>
<ServiceStatus>
<StatusNbr>304</StatusNbr>
<StatusDescription>Address Not Found</StatusDescription>
</ServiceStatus>
<ServiceResult />
</VerificationResult>
</VerificationResponse>
</WebServiceResponse>
你可以使用这样的东西(使用 Linq-to-XML)
// define the XML namespace of the <VerificationResponse> node and down
XNamespace wwwabc = "www.abc.com";
// parse your XML into a XDocument
XDocument xdoc = XDocument.Parse(your-xml-input);
// get the <StatusDescription> node(s) from the XDocument
// here I'm assuming there's only one such node, so I'm using
// the .FirstOrDefault() method to fetch it
var statusDescriptionNode = xdoc.Descendants(wwwabc + "StatusDescription").FirstOrDefault();
// if we found a first such node
if (statusDescriptionNode != null)
{
string statusDescription = statusDescriptionNode.Value;
}
当然,如果这是一个非常大且复杂的 XML,那么 .Descendants()
调用可能不是很有效(它只是在整个 XML 文档中搜索节点该名称空间 + 节点名称)。
您的 xml 包含命名空间并使用 XDocument,您可以通过以下方式获得所需的节点值:
XDocument doc = XDocument.Parse(xml);
XNamespace xmlNamespace = "www.abc.com";
var ResultNode = from a in doc.Descendants(xmlNamespace + "VerificationResponse").Descendants(xmlNamespace + "StatusDescription")
select a.Value;
我无法获取值。
如何获取StatusDescription
值?请告诉我。
<WebServiceResponse xmlns="ws.abc.com">
<SubscriptionInfo xmlns="ws.abc.com">
<LicenseStatusCode>0</LicenseStatusCode>
<Amount>0</Amount>
</SubscriptionInfo>
<VerificationResponse xmlns="www.abc.com">
<VerificationResult>
<ServiceStatus>
<StatusNbr>304</StatusNbr>
<StatusDescription>Address Not Found</StatusDescription>
</ServiceStatus>
<ServiceResult />
</VerificationResult>
</VerificationResponse>
</WebServiceResponse>
你可以使用这样的东西(使用 Linq-to-XML)
// define the XML namespace of the <VerificationResponse> node and down
XNamespace wwwabc = "www.abc.com";
// parse your XML into a XDocument
XDocument xdoc = XDocument.Parse(your-xml-input);
// get the <StatusDescription> node(s) from the XDocument
// here I'm assuming there's only one such node, so I'm using
// the .FirstOrDefault() method to fetch it
var statusDescriptionNode = xdoc.Descendants(wwwabc + "StatusDescription").FirstOrDefault();
// if we found a first such node
if (statusDescriptionNode != null)
{
string statusDescription = statusDescriptionNode.Value;
}
当然,如果这是一个非常大且复杂的 XML,那么 .Descendants()
调用可能不是很有效(它只是在整个 XML 文档中搜索节点该名称空间 + 节点名称)。
您的 xml 包含命名空间并使用 XDocument,您可以通过以下方式获得所需的节点值:
XDocument doc = XDocument.Parse(xml);
XNamespace xmlNamespace = "www.abc.com";
var ResultNode = from a in doc.Descendants(xmlNamespace + "VerificationResponse").Descendants(xmlNamespace + "StatusDescription")
select a.Value;