【问题标题】:Load xml file from path in WCF Web Service从 WCF Web 服务中的路径加载 xml 文件
【发布时间】:2018-02-06 15:21:19
【问题描述】:

试图打开这个测试文件,它存在于我的解决方案下的一个文件夹中:

C:\dev\trunk\Development\WebSvc\WCFProj\Xml\po.xml

我的 c# 方法是:

 public XmlDocument generateXmlResponse()
        {
            string appDir = AppContext.BaseDirectory;
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(@"Xml\ResponseTempl.xml");

            return xml;
        }

异常信息是:

  "Data at the root level is invalid. Line 1, position 1."

现在当我单步执行代码时,我可以使用相对路径:

appDir + @"Xml\po.xml"

正确解析为:

C:\dev\trunk\Development\WebSvc\WCFProj\Xml\po.xml

我刚刚从 ms 网站 https://msdn.microsoft.com/en-us/library/bb343181(v=vs.110).aspx 中获取了样本 PurchaseOrder.xml

<PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">
  <Address Type="Shipping">
    <Name>Ellen Adams</Name>
    <Street>123 Maple Street</Street>
    <City>Mill Valley</City>
    <State>CA</State>
    <Zip>10999</Zip>
    <Country>USA</Country>
  </Address>
  <Address Type="Billing">
    <Name>Tai Yee</Name>
    <Street>8 Oak Avenue</Street>
    <City>Old Town</City>
    <State>PA</State>
    <Zip>95819</Zip>
    <Country>USA</Country>
  </Address>
  <DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes>
  <Items>
    <Item PartNumber="872-AA">
      <ProductName>Lawnmower</ProductName>
      <Quantity>1</Quantity>
      <USPrice>148.95</USPrice>
      <Comment>Confirm this is electric</Comment>
    </Item>
    <Item PartNumber="926-AA">
      <ProductName>Baby Monitor</ProductName>
      <Quantity>2</Quantity>
      <USPrice>39.98</USPrice>
      <ShipDate>1999-05-21</ShipDate>
    </Item>
  </Items>
</PurchaseOrder>

【问题讨论】:

  • XmlDocument.LoadXml() 用于加载 Xml Snippet。使用XmlDocument.Load 加载文件。
  • 确实如此。谢谢你。实际上,您应该发布该答案。
  • 我敢肯定在某个地方有一个骗子——我过去常常把它们混在一起。出于兴趣,您可以考虑XDocument,即 XmlDocument 的 LINQ 友好继任者?
  • @StuartLC - 是的,这也有效。我可以使用XDocument.Load(appDir + @"Xml\ResponseTempl.xml"); 加载 xml 文件

标签: c# .net c#-4.0


【解决方案1】:

这里的问题是以下行:

xml.LoadXml(@"Xml\ResponseTempl.xml");

正在尝试将字符串加载为 XML 并给出错误,因为它是无效的 XML。 LoadXml 应该像这样使用:

xml.LoadXml("<item><name>wrench</name></item>");

由于您尝试从需要使用的文件中读取: https://msdn.microsoft.com/en-us/library/875kz807(v=vs.110).aspx

这将如下所示:

xml.Load(@"Xml\ResponseTempl.xml");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2020-10-27
    相关资源
    最近更新 更多