我想从xml字符串中删除xmlns部分并将其转换为json。
string test = "<Behavior xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.adlibsoftware.com\">\r\n <JobFolders>\r\n <Error>${machine:description=RM1029-DEV:id=4FC4AF7C-AF61-45F9-BE86-49812C619F06}</Error>\r\n <Work>${machine:description=RM1029-DEV:id=4FC4AF7C-AF61-45F9-BE86-49812C619F06}</Work>\r\n <Input>\r\n <DeleteEmptySubfolders>true</DeleteEmptySubfolders>\r\n </Input>\r\n </JobFolders>\r\n <JobFiles>\r\n <ProcessingLocation>\r\n <Server>\r\n <TransferSegmentSize unit=\"Kilobytes\">4096</TransferSegmentSize>\r\n </Server>\r\n </ProcessingLocation>\r\n <Input>\r\n <Naming>Resh</Naming>\r\n </Input>\r\n </JobFiles>\r\n</Behavior>";
我尝试使用下面的代码,但仍然无法删除它。任何帮助将是伟大的!
XmlDocument doc = new XmlDocument();
doc.LoadXml(test);
foreach (var node in doc)
{
var el = node as XmlElement;
if (el != null)
{
if (el.HasAttribute("xmlns"))
{
var ns = el.GetAttribute("xmlns");
if (ns != null && ns == el.NamespaceURI)
{
el.RemoveAttribute("xmlns");
}
}
}
}
string jsonText = JsonConvert.SerializeXmlNode(doc);
我期望的输出是:
{"Behavior":"JobFolders":{"Error":"${machine:description=RM1029-DEV:id=4FC4AF7C-AF61-45F9-BE86-49812C619F06}","Work":"${machine:description=RM1029-DEV:id=4FC4AF7C-AF61-45F9-BE86-49812C619F06}","Input":{"DeleteEmptySubfolders":"true"}},"JobFiles":{"ProcessingLocation":{"Server":{"TransferSegmentSize":{"@unit":"Kilobytes","#text":"4096"}}},"Input":{"Naming":"Resh"}}}}
我从上面的代码收到的输出:
{"Behavior":{"@xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","JobFolders":{"Error":"${machine:description=RM1029-DEV:id=4FC4AF7C-AF61-45F9-BE86-49812C619F06}","Work":"${machine:description=RM1029-DEV:id=4FC4AF7C-AF61-45F9-BE86-49812C619F06}","Input":{"DeleteEmptySubfolders":"true"}},"JobFiles":{"ProcessingLocation":{"Server":{"TransferSegmentSize":{"@unit":"Kilobytes","#text":"4096"}}},"Input":{"Naming":"Resh"}}}}
2条答案
按热度按时间xoefb8l81#
问题解决了我在这里添加了编辑的解决方案。谢谢你的时间!
fhity93d2#
问题中的代码仅删除每个节点的1个属性。
这段代码实际上是在删除属性: