如何使用c#从xml文件中提取特定属性?

时间:2016-07-15 04:51:51

标签: c# .net

static void Main(string[] args)
        {

            WebClient _httpReq = new WebClient(); // to talk to the web only for get method
            string response = _httpReq.DownloadString("https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Patient?family=Argonaut&given=Jason");
Console.WriteLine(response);\\prints the xml string fetched from FHIR provider EPIC
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(response); // suppose that myXmlString contains "<Names>...</Names>"

            XmlNodeList xnList = xml.SelectNodes("/entry/resource/patient/name");
// here code is trying to extract the name attribute
            foreach (XmlNode xn in xnList)
            {
                string firstName = xn["family value"].InnerText;
                string lastName = xn["given value"].InnerText;
                Console.WriteLine("Name: {0} {1}", firstName, lastName);
              //print the first name and last name of the patient
            }
            Console.ReadLine();

        }

2 个答案:

答案 0 :(得分:1)

我是这样做的:

XmlDocument MyDocument = new XmlDocument();
MyDocument.Load("...");

XmlNode MyNode = MyDocument.SelectSingleNode("/Node_Name");

foreach (XmlAttribute MyAttribute in MyNode.Attributes)
{
    if (MyAttribute.Name == "Attribute_Name")
    {
        object Value = MyAttribute.Value;
        break;
    }
}

答案 1 :(得分:0)

回顾XPath。一旦你开始理解它,你会发现编码比迭代列表更有效,更容易。它还允许您直接获取所需的节点/属性。

然后代码类似于

string attrVal = doc.SelectSingleNode("/entry/resource/patient/@name").Value;

或者您可以在XMlDocument中加载XML,并且您可以获取元素,并且可以读取特定atairbute的元素,

XmlDocument doc = new XmlDocument();
doc.LoadXml("<reply success=\"true\">More nodes go here</reply>");

XmlElement root = doc.DocumentElement;

string s = root.Attributes["success"].Value;