获取除根元素之外的整个XML

时间:2012-11-13 00:18:10

标签: c# xml linq

<Employees>
  <Product_Name>
    <hello1>product1</hello1>
    <hello2>product2</hello2>
    <hello3>product3</hello3>
    <hello4>product4</hello4>
  </Product_Name>
  <product_Price>
    <hello1>111</hello1>
    <hello2>222</hello2>
    <hello3>333</hello3>
    <hello4>444</hello4>
  </product_Price>
</Employees>

是否可以使用C#将以下XML转换为下面显示的XML。我尝试使用删除功能但它没有用。我也试图获取根节点的值。没工作

  <Product_Name>
    <hello1>product1</hello1>
    <hello2>product2</hello2>
    <hello3>product3</hello3>
    <hello4>product4</hello4>
  </Product_Name>
  <product_Price>
    <hello1>111</hello1>
    <hello2>222</hello2>
    <hello3>333</hello3>
    <hello4>444</hello4>
  </product_Price>

3 个答案:

答案 0 :(得分:3)

如果您只想获取内部xml,可以使用XmlReader的ReadInnerXml。将innerXML作为字符串提取(跳过根节点)。

var xmlReader = XElement.Load("data.xml").CreateReader();
xmlReader.MoveToContent();
string innerXml = xmlReader.ReadInnerXml();

答案 1 :(得分:1)

您可以将其存储为XmlNodeList以使其格式正确。以下是如何执行此操作的示例:

XmlDocument xml= new XmlDocument();
        xml.LoadXml(@"<Employees>
                      <Product_Name>
                        <hello1>product1</hello1>
                        <hello2>product2</hello2>
                        <hello3>product3</hello3>
                        <hello4>product4</hello4>
                      </Product_Name>
                      <product_Price>
                        <hello1>111</hello1>
                        <hello2>222</hello2>
                        <hello3>333</hello3>
                        <hello4>444</hello4>
                      </product_Price>
                    </Employees>");
        var nodeList = xml.SelectNodes("Employees");
        foreach (XmlNode node in nodeList)
        {
           Console.WriteLine(node.InnerXml); //this will give you your desired result
        }

答案 2 :(得分:1)

如果您可以访问Linq to XML,那么您应该XDocument 警告:我相信你的xml格式不正确 - 你应该有类似的东西:

<?xml version="1.0" encoding="utf-8"?>

将第一个xml标记添加到xml。

string xml = @"<?xml version="1.0" encoding="utf-8"?>
               <Employees>
                 <Product_Name>
                    <hello1>product1</hello1>
                    <hello2>product2</hello2>
                    <hello3>product3</hello3>
                    <hello4>product4</hello4>
                 </Product_Name>
                 <product_Price>
                    <hello1>111</hello1>
                    <hello2>222</hello2>
                    <hello3>333</hello3>
                    <hello4>444</hello4>
                 </product_Price>
              </Employees>";

XDocument xDoc = XDocument.Parse(xml);

// get the elements
var rootElements = xDoc.Root.Elements();

或者,您可以从文件中加载xml:

XDocument xDoc = XDocument.Load("xmlFile.xml");