解析XML linq命名空间问题

时间:2012-09-04 05:07:39

标签: asp.net xml linq linq-to-xml

使用Linq to XML解析我正在解析的XML。使用下面的代码但什么都没得到

<?xml version="1.0" encoding="utf-8"?> 
    <!--ADOR Acknowledgement 2-->  
    <AckTransmission xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.irs.gov/efile"> 
      <TransmissionHeader recordCount="1"> 
        <Jurisdiction>ALABAMA</Jurisdiction> 
        <TransmissionId>1946157056</TransmissionId> 
        <Timestamp>2012-08-16T01:25:47-05:00</Timestamp> 
        <Transmitter> 
          <ETIN>00000</ETIN> 
        </Transmitter> 
        <ProcessType>T</ProcessType> 
        <AgentIdentifier>ACK</AgentIdentifier> 
      </TransmissionHeader> 
      <Acknowledgement> 
        <SubmissionId>X1684956672</SubmissionId> 
        <EFIN>X16849</EFIN> 
        <GovernmentCode>ALST</GovernmentCode> 
        <SubmissionType>XMLTOM</SubmissionType> 
        <TaxYear>9999</TaxYear> 
        <SubmissionCategory>MFET</SubmissionCategory> 
        <AcceptanceStatus>A</AcceptanceStatus> 
        <ContainedAlerts>0</ContainedAlerts> 
        <StatusDate>2012-08-16</StatusDate> 
      </Acknowledgement> 
    </AckTransmission>

我正在尝试使用Linq来解析此XML

使用

var 

q1 = from c1 in TheDocument1.Descendants("{http://www.irs.gov/efile}AckTransmission")
                         select new
                         {
                             Jurisdiction = c1.Element("{http://www.irs.gov/efile}Jurisdiction").Value,
                             TransmissionId = c1.Element("{http://www.irs.gov/efile}TransmissionId").Value,
                             ETIN = c1.Element("{http://www.irs.gov/efile}Transmitter").Element("{http://www.irs.gov/efile}ETIN").Value,
                             lTimestamp = c1.Element("{http://www.irs.gov/efile}Timestamp").Value,
                             ProcessType = c1.Element("{http://www.irs.gov/efile}ProcessType").Value,
                             AgentIdentifie = c1.Element("{http://www.irs.gov/efile}AgentIdentifier").Value,

                             GovernmentCode = c1.Element("{http://www.irs.gov/efile}GovernmentCode").Value,
                             SubmissionType = c1.Element("{http://www.irs.gov/efile}SubmissionType").Value,
                             TaxYear = c1.Element("{http://www.irs.gov/efile}TaxYear").Value,
                             StatusDate = c1.Element("{http://www.irs.gov/efile}StatusDate").Value
                         };

但是什么都没有,我尝试了很多东西而且输了。请帮我。提前致谢

1 个答案:

答案 0 :(得分:0)

创建名称空间对象并将其与元素/节点一起使用。

 XNamespace ns = "http://www.irs.gov/efile";
 XDocument doc=XDocument.Load(file);


 var result = doc.Descendants(ns + "AckTransmission").Select(p => new
 {
  Jurisdiction = (string)p.Element(ns + "TransmissionHeader").Element(ns + "Jurisdiction"),
  TransmissionId = (string)p.Element(ns + "TransmissionHeader").Element(ns + "TransmissionId")
 });