简体   繁体   English

从特定节点读取 XML 元素

[英]Read XML elements from a specific node

Here the XML file这里是 XML 文件

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<MyResponse xmlns="http://mynamespace">
    <Header>
        <FirstName>David</FirstName>
        <LastName>Duchovny</LastName>
    </Header>
    <Filmography>
        <Films>     
        </Films>
        <Series>
            <Serie>
                <Title>X-Files</Title>
                <Year>1989</Year>
            </Serie>
        </Series>

    </Filmography>  
</MyResponse>

I'd like only get the Header section to this object:我只想得到这个 object 的Header部分:

public class Header
{
    public string FirstName { get; set; }

    public string LastName { get; set; }
}

I did this:我这样做了:

const string nameSapce = "http://mynamespace">
var xmlDocument = new XmlDocument();
xmlDocument.Load(@"c:\temp\csv.xml");
var namespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
namespaceManager.AddNamespace("myApplication", nameSapce);
XmlNode node = xmlDocument.DocumentElement.SelectSingleNode("//myApplication:MyResponse", namespaceManager);
Console.WriteLine(node);

I get this as result in the node variable:我在node变量中得到了这个结果:

<Header xmlns="http://mynamespace">
    <FirstName>David</FirstName>
    <LastName>Duchovny</LastName>
</Header>

How can I extract the Header item to the Header object?如何将Header项目提取到Header object?

Have you tried LINQ to XML , you can use it with the select the Header class from the xml Object, Have you tried LINQ to XML , you can use it with the select the Header class from the xml Object,

Exemples: https://docs.microsoft.com/en-us/dotnet/standard/linq/linq-xml-overview示例: https://docs.microsoft.com/en-us/dotnet/standard/linq/linq-xml-overview

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

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