简体   繁体   English

从XML文件获取属性

[英]Get attribute from XML file

I have an XML file with this structure : 我有一个具有以下结构的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<DocumentInterface transactionNo="0102014146" creationDate="2014-05-26" version="1.4" ilnSender="4306286000007" ilnRecipient="407731000008" creationTime="17:00:30" xsi:schemaLocation="http://xmlschema.metro-mgp.com/outdoc/DocumentInterface DocumentInterface.xsd" xmlns="http://xmlschema.metro-mgp.com/outdoc/DocumentInterface" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CheckSum>
    <DocCount>1</DocCount>
    <PayableAmount>682.38</PayableAmount>
</CheckSum>
 ......
    </DocumentInterface>

I need to modify the attribute transactionNo. 我需要修改属性transactionNo。 From c# I try to get the value from file with this code: 从C#中,我尝试使用以下代码从文件中获取值:

       XmlDocument doc = new XmlDocument();
        using (FileStream fs = new FileStream(newFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
        {

            doc.PreserveWhitespace = true;
            doc.Load(fs);
        }

        XmlAttribute formTransactionNo = (XmlAttribute)doc.SelectSingleNode("//DocumentInterface/@transactionNo");
        if (formTransactionNo != null)
        {
             prmNewValue=formTransactionNo.Value;
        }

But always formTransactionNo is null.Can you help me to get this value? 但是formTransactionNo总是为null。你能帮我得到这个值吗? Thanks 谢谢

You cannot select attribute with XPath. 您不能使用XPath选择属性。 Actually you don't need XPath here - its easy to get attribute from root element: 实际上,您这里不需要XPath-它很容易从根元素获取属性:

XmlAttribute transactionNo = doc.DocumentElement.Attributes["transactionNo"];
string prmNewValue = transactionNo.Value;
// output: 0102014146

Updating attribute value is also simple: 更新属性值也很简单:

transactionNo.Value = "007";
doc.Save(path_to_xml);

BTW consider to use modern LINQ to XML approach for parsing/updating xml. BTW考虑使用现代LINQ to XML方法来解析/更新xml。 Eg getting this attribute value will look like: 例如,获取此属性值将如下所示:

var xdoc = XDocument.Load(newFileName);    
var prmNewValue = (string)xdoc.Root.Attribute("transactionNo");

Or getting payable amount 或获得应付金额

var ns = xdoc.Root.GetDefaultNamespace();
var payableAmount = 
    (decimal)xdoc.Root.Element(ns + "CheckSum").Element(ns + "PayableAmount");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM