我想知道如何获取Xml文件的nodepath。我贴在下面。所以我想创建一个方法,它将接受一个节点路径,并返回nodepath指向的元素的xml。
问题是我想要FormA1的xml,它位于元素Member下面(在Member / MemberName / BusinessNameLine1Txt下有Mouser0),我怎么能得到它,因为xml还有另一个Member元素(虽然有不同的BusinessNameLine1Txt = Mouser1)。
<ReturnState>
<ReturnDataState>
<Form6>
<Header>
<BusinessActivityCode>423690</BusinessActivityCode>
<StateOfIncorporation>
<State>DE</State>
<YearOfIncorporation>2006</YearOfIncorporation>
</StateOfIncorporation>
</Header>
<Body>
<EstTaxPmtLessRefund>492823</EstTaxPmtLessRefund>
<Overpayment>118450</Overpayment>
<OverpaymentCreditedNxtYr>118450</OverpaymentCreditedNxtYr>
<Reconciliation></Reconciliation>
<SignatureArea></SignatureArea>
<Member>
<MemberName>
<BusinessNameLine1Txt>Mouser0</BusinessNameLine1Txt>
</MemberName>
<FormA1>
<PartI-SalesFactor>
<SalesDelOrShippedOutState>31754631</SalesDelOrShippedOutState>
<TotalSales>
<Wisconsin>31754631</Wisconsin>
<TotalCompany>1965873635</TotalCompany>
</TotalSales>
<SalesFactorTotal>
<Wisconsin>31754631</Wisconsin>
<TotalCompany>1965873635</TotalCompany>
</SalesFactorTotal>
<ApportionmentPercentage>0.000000</ApportionmentPercentage>
</PartI-SalesFactor>
</FormA1>
</Member>
<Member>
<MemberName>
<BusinessNameLine1Txt>Mouser1</BusinessNameLine1Txt>
</MemberName>
<FormA1>
<PartI-SalesFactor>
<SalesDelOrShippedOutState>31754632</SalesDelOrShippedOutState>
<TotalSales>
<Wisconsin>31754632</Wisconsin>
<TotalCompany>1965873633</TotalCompany>
</TotalSales>
<SalesFactorTotal>
<Wisconsin>31754632</Wisconsin>
<TotalCompany>196587344</TotalCompany>
</SalesFactorTotal>
<ApportionmentPercentage>1.000000</ApportionmentPercentage>
</PartI-SalesFactor>
</FormA1>
</Member>
</Body>
</Form6>
</ReturnDataState>
</ReturnState>
所以,如果我将方法传递给路径,
ReturnState / ReturnDataState / Form6 / Body / Member / FormA1并希望它返回
<FormA1>
<PartI-SalesFactor>
<SalesDelOrShippedOutState>31754631</SalesDelOrShippedOutState>
<TotalSales>
<Wisconsin>31754631</Wisconsin>
<TotalCompany>1965873635</TotalCompany>
</TotalSales>
<SalesFactorTotal>
<Wisconsin>31754631</Wisconsin>
<TotalCompany>1965873635</TotalCompany>
</SalesFactorTotal>
<ApportionmentPercentage>0.000000</ApportionmentPercentage>
</PartI-SalesFactor>
</FormA1>
而不是其他成员元素下的其他FormA1。我该怎么做?
非常感谢提前!!
AJ。
答案 0 :(得分:1)
您可以使用这样的XPath查询:
var xElement = XElement.Parse(str); //or however you load your xml document
var formA1 = xElement.XPathSelectElement("ReturnDataState/Form6/Body/Member/FormA1");
Console.WriteLine(formA1.ToString());
因为我使用XPathSelectElement
代替XPathSelectElements
,所以您只会获得第一个匹配元素。如果您想根据其他条件选择结果,可以使用xpath的其他技巧,例如position()
选择器。
答案 1 :(得分:1)
.net有几种方法可以针对XML文档运行XPath,有一种方法在the other answer中被StriplingWarrior提到,所以我相信xpath是这里的方法。您可以使用XPath谓词([...]
)仅返回满足特定条件的元素。例如,您可以使用以下XPath表达式仅获取具有值等于Member
的祖母BusinessNameLine1Txt
的{{1}}元素:
"Mouser0"
话虽如此,获得此类Member[MemberName/BusinessNameLine1Txt='Mouser0']
父级的FormA1
元素的完整XPath表达式如下:
Member
<强> xpathtester.com demo
强>