【问题标题】:How to read XML values using string methods of Java如何使用 Java 的字符串方法读取 XML 值
【发布时间】:2014-04-24 15:35:51
【问题描述】:

我正在寻找一种从以下搜索字符串值的方法

<Test>
<Name>XYZ</Name>
<City>London</City>
</Test>

请注意,标签不会重复

以上内容存储在一个字符串中。我想写一个 java 方法来做这样的事情:

tagvalue = getvalue(<TagName>)

for example tagvalue=getvalye(Name)

另外,我想要一个返回根标签(字符串中的第一个标签)的方法,即它应该返回"Test"

我知道 Java 解析器和 DOM 可以完成这项任务,但我不想使用它们。我可以简单地通过字符串操作方法来做到这一点吗?还是其他方法?

我正在尝试的解决方案如下:

//Method Call
String tag_value = getvalue(databuffer,"Name");

//Method

    private String getvalue(String Content, String Tagname) 
     {

            if (Content.contains("<"+Tagname+">"))
                {
                      if(Content.contains("</"+Tagname+">"))
                        {
                          //How do I get Tag value here? 
                 return Tagvalue;
                        }
                    }
        }

正在尝试的另一个解决方案是:

//method 
    private String getvalue(String Content, String Tagname)
        {
                //<Name>XYZ</Name> 
            int Starttag = Content.indexOf("<"+Tagname+">");//Returns 0
            int Endtag   = Content.indexOf("</"+Tagname+">");//Returns 9 
                //How to find the total length of <Starttag> so that I can subtract it with the index of Endtag to get the value?
            return ;
        }

我可以从任何人那里得到任何帮助吗?

//我已经更新了元素名称中命名空间的问题...

输入文件如下所示

<ns:Test>
<ns:Name>XYZ</ns:Name>
<ns:City>London</ns:City>
</ns:Test>

注意:我不知道即将到来的命名空间?它可能是 ns 或 np ......任何东西..如何处理?我知道的一件事是分隔符将是“:”

是否可以使用字符串方法简单地忽略元素名称中的命名空间来获取以下逻辑中的元素值?

方法调用: String elementvalue = getElementvalue(databuffer,"Name")

方法:

public String getvalue(String buffer, String tagname) 
    {   
        String startTag, endTag,elementdata = null;
        int startposition,endposition;
        try 
        {
            startTag     = "<"+ tagname + ">";
            endTag       = "</"+ tagname + ">";
            startposition         = buffer.indexOf(startTag);       
            startposition         = startposition + startTag.length();
            endposition      = buffer.indexOf(endTag); 
            elementdata =  buffer.substring(startposition, endposition);
        }
        return elementdata;
    }

如果有人可以帮助我,请告诉我?

【问题讨论】:

  • 你可以通过字符串读取来做到这一点,递归可能是最好的:读取元素的开始,找到元素的结束,并递归地为子标签做同样的事情。
  • 您能否向我们展示您为尝试实现需求而编写的代码
  • I know Java parser and DOM can do this task but I don't want to use them 为什么不想使用为您完成解析工作的库?
  • @jedison 如果您有两个相同的标签,您可能会遇到问题。取决于他们确定标签不重复的程度。
  • @Trengot,我只是基于“注意:标签不会重复。”

标签: java xml string


【解决方案1】:

【讨论】:

  • 感谢您的回复..我正在寻找一些使用字符串操作的方法。
  • 在我看来,正则表达式只不过是字符串操作而已。它们通常为仅使用 String API 需要几行代码的任务提供智能解决方案。
【解决方案2】:

您可以通过字符串读取来做到这一点,递归可能是最好的:读取元素的 start ,找到元素的 end ,并递归地对子标签执行相同的操作。如其他地方所述,如果标签重复,这可能会导致问题。

【讨论】:

  • 这正是我的想法..你能提供一些示例代码来执行这个操作吗...我是java新手..
  • 我有点犹豫要不要这样做,因为这通常是 .equals("homework assignment")。我们(StackOverflow 上的大多数人)更喜欢您尝试一下并在遇到困难时寻求帮助。阅读字符串寻找“”。那是您的标签名称;然后找到与此标签名称匹配的“”。当然,人们(正确地)建议使用 DOM、JaxB 和 RegEx 等其他工具。
  • 为此道歉...这不是家庭作业...但是感谢伪逻辑...我会尝试实现它...再次感谢您的时间。
  • 好的,我可以为您提供一些代码或查看您编写的代码。
  • 我已经编写了我的代码......我正在尝试......你能检查一下吗?
【解决方案3】:

您也可以使用 JAXB 来执行此操作。它需要更多的前期工作,但这是正确的方法。下一个最好的事情是 Java DOM 操作,即使您不想使用它。

使用正则表达式或字符串操作很危险,因为您的 XML 可能会发生变化。

看看这个article

【讨论】:

  • 感谢您的回复。我正在寻找一些通过字符串操作的方法,因为我的 XML 永远不会改变,结构也不会改变。
【解决方案4】:

使用indexOf(...) 代替contains(...) 并捕获返回值。然后就可以使用substring(...)获取标签值了。

【讨论】:

    【解决方案5】:

    输入文件

    <Test>
    <Name>XYZ</Name>
    <City>London</City>
    </Test>
    

    方法调用: tagvalue = getvalue(databuffer,"Name");

    方法

    public String getvalue(String buffer, String tagname) 
        {   
            String startTag, endTag,elementdata = null;
            int startposition,endposition;
            try 
            {
                startTag     = "<"+ tagname + ">";
                endTag       = "</"+ tagname + ">";
                startposition         = buffer.indexOf(startTag);       
                startposition         = startposition + startTag.length();
                endposition      = buffer.indexOf(endTag); 
                elementdata =  buffer.substring(startposition, endposition);
            }
            return elementdata;
        }
    

    【讨论】:

      【解决方案6】:

      您的第二个解决方案更优雅。我修改了您的代码并添加了一些 cmets,以便您更好地了解如何去做。

      private static String getvalue(String content, String tagname)
      {
          // <ns:Name>XYZ</ns:Name> 
          int tagOpenIndex = content.indexOf(tagname + ">"); //returns the start index of the opening tag or -1 if it was not found
          int tagCloseIndex   = content.indexOf("</", tagOpenIndex); //returns the start index of the closing tag or -1 if it was not found
          String res = null;
         // How to find the total length of <Starttag> so that I can subtract it with the index of Endtag to get the value?
          if(tagOpenIndex != -1 && tagCloseIndex != -1 && content.indexOf(":" + tagname, tagCloseIndex) != -1){ // Firstly, you should be sure the opening and closing tags were both found in the String
               // The length of the opening tag = the length of the tag itself + 1 (the closing delimiter ">")
              int lenOpenTag = tagname.length() + 1;
              // the start index of the value enclosed in the tags is the start index of the opening tag + the length of the opening tag 
              int valueStartIndex = tagOpenIndex + lenOpenTag; 
              // you simply get the substring between the valueStartIndex and the start index of the closing tag
              res = content.substring(valueStartIndex, tagCloseIndex);
          }
          return res;
      }
      

      建议: try and cultivate the habit of starting your variable names with small letters except for constants.

      【讨论】:

      • 你能看到我更新的关于元素名称中命名空间的问题吗?
      • @user3384231 我刚刚更新了处理命名空间的答案。
      猜你喜欢
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多